0
我正在玩写二叉树。目前它不会完整,或者每个级别都已满。我只是试图让插入工作在最基本的形式(我会在后面重新排序)。PHP二叉树插入问题
守则
<?php
class Node {
public $left = NULL;
public $right = NULL;
public $data = NULL;
}
class BinaryTree {
private $root = NULL;
public function insert($value, $node = false) {
echo "VALUE: $value \n";
if($node === false) {
$node = $this->root;
}
if($node->data === NULL) { // Always stuck here.
$node->data = $value;
} else {
if($value <= $node->data) {
$this->insert($value, $node->left);
} else if($value >= $node->data) {
$this->insert($value, $node->right);
}
}
}
}
$t = new BinaryTree();
$t->insert(7);
$t->insert(6);
$t->insert(1);
?>
的问题是,当我分配$节点 - >有价值的东西,在$节点对象似乎并没有被正确地得到传递到插入()函数。正因为如此,它永远不会通过根。
编辑
@Joost指出我错过了几步。这导致我在我的BinaryTree类中的以下内容:
public function __construct() {
$this->root = new Node();
}
public function insert($value, $node = false) {
if($node === false) {
$node = $this->root;
}
if($node->data === NULL) {
$node->data = $value;
} else {
if($value <= $node->data) {
if(get_class($node->left) != "Node") {
$node->left = new Node();
}
$this->insert($value, $node->left);
} else if($value >= $node->data) {
if(get_class($node->right) != "Node") {
$node->rght = new Node();
}
$this->insert($value, $node->right);
}
}
}
啊,我知道我错过了什么!谢谢。 – 2012-07-15 21:11:23