PHP - 递归二叉树

时间:2013-08-19 02:56:01

标签: php binary-tree binary-search-tree

我一直在尝试探索PHP的潜力,所以我试着看看我是否可以实现二叉树结构。这是代码:

class Node{
    public $leftNode;
    public $rightNode;
    public $value;
    public function Node($value){
        $this->value = $value;
    }
}

class binTree{
    public function inserter(Node $node, $value){
        if($value < $node->value){
            if($node->leftNode != null){
                inserter($node, $value);
            }
            else{
                $node->leftNode = new Node($value);
            }
        }
        else if($value > $node->value){
            if($node->rightNode != null){
                inserter($node, $value);
            }
            else{
                $node->rightNode = new Node($value);
            }
        }
    }   
}

现在由于某种原因,当我尝试在其内部调用插入器函数(即插入器($ node,$ value)时,我收到此错误:Fatal error: Call to undefined function inserter().所以我尝试通过$ this引用它,甚至binTree ::没有运气。我分别得到Fatal error: Using $this when not in object contextFatal error: Allowed memory size of 134217728 bytes exhausted错误。有人可以解释发生了什么吗?

2 个答案:

答案 0 :(得分:0)

我怀疑你的问题如下:

php构造函数以这种方式工作

public function __construct ()
{

}

(与您正在使用的C#类似的语法)

答案 1 :(得分:0)

试试这个:

<?php
class Node{
    public $leftNode;
    public $rightNode;
    public $value;

    // changed the constructor name from "Node" to "__construct"
    public function __construct($value){
        $this->value = $value;
    }
}

class binTree{
    public function inserter(Node $node, $value){
        if($value < $node->value){
            if($node->leftNode != null){
                // added "$this->"
                $this->inserter($node, $value);
            }
            else{
                $node->leftNode = new Node($value);
            }
        }
        else if($value > $node->value){
            if($node->rightNode != null){
                // added "$this->"
                $this->inserter($node, $value);
            }
            else{
                $node->rightNode = new Node($value);
            }
        }
    }
}

$binTree = new binTree();
$binTree->inserter(new Node('foo'), 'bar');