![](/img/trans.png)
[英]Find insert position and number of childs in a binary tree using php mysql
[英]PHP Binary Tree Insert Issue
我正在玩寫二叉樹。 目前它不會是完整的,或者每個級別都是完整的。 我只是想讓插件工作在它最基本的形式(我會在那之后重新訂購)。
編碼
<?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);
?>
問題是當我分配$ node-> value之類的東西時,$ node對象似乎沒有正確地傳遞給insert()函數。 因此,它永遠不會通過根。
編輯
@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);
}
}
}
它不起作用,因為您從不初始化根。 如果根目錄尚未設置,則可以使用始終為空的根(在__construct
初始化它)或直接將新節點分配給插入的根。
實際上,這個問題適用於所有節點。 您永遠不會創建Node
實例,也不Node
設置為父節點的子節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.