我想使用 PHP 构建一棵二叉树。但是由于 PHP 中没有指针,我如何构建一棵树。
对于树中的每个节点都必须具有以下属性:
1.节点处的值
2.节点级别
3.指向右 child 的指针
4.指向左 child 的指针
但是由于 PHP 中没有指针,我不知道如何以及从哪里开始。我所知道的是,如果我们使用 $a=&$b,那么两者将指向同一个对象,并且它们不像 C 中的指针。 请建议我几种使用 PHP 构建二叉树的方法。
最佳答案
诀窍是 php 数组可以有另一个数组作为元素。
无需使用类即可完成
$root = array(0,0)
$root[0] = $firstval; // Value
$root[1] = 0; // level 0
// first child on left
$lchild = array($lvalue,1); // left value and level 1
$root[2] = $lchild; // attach to root item
// first right child
$rchild = array($rvalue,1); // right value and level 1
$root[3] = $rchild; // attach to root item;
//print value of right child:-
print $root[3][0];
// or more usefull
$anode = $root[3];
print "Value " + $anode[0];
if (isset($anode[2]) ) {
print "has left child";
}
对于类,您只需定义一个类,其中包含值、级别、左分支的类的另一个实例以及右分支的类的另一个实例。它实际上与上面的纯数组实现相同,但更易于阅读。
关于php - 使用 PHP 的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7643039/