2012-07-15 94 views
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); 
     } 
    } 
} 

回答

2

它不工作,因为你永远不会初始化根。您可以使用始终为空的根(在__construct中初始化它),或者如果根目录尚未设置,则可以直接向插入的根分配新节点。

实际上,这个问题对于所有节点都是正确的。您从不创建Node实例,您也不会将节点设置为父项的子项。

+0

啊,我知道我错过了什么!谢谢。 – 2012-07-15 21:11:23