저는 이진 트리를 작성하는 중 놀고 있습니다. 현재는 완전하지 않을 수도 있고, 각 레벨이 가득 채워져있을 수도 있습니다. 나는 그저 인서트를 가장 기본적인 형태로 작동 시키려고 노력하고있다. (나는 그 이후에 다시 순서를 정한다.)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);
}
}
}
아아, 내가 놓친 걸 알았어! 감사. –