您好,欢迎访问一九零五行业门户网

php怎么实现二叉树的存储

php如何实现二叉树的存储?
就像上面图片里面所画的一样,我怎么把那一串数字用二叉树存起来?用php实现。
求大神帮忙呀!!!!
==========初学二叉树
------解决方案--------------------
这个很简单
class node{
public var $per;
public var $lnode;
public var $rnode;
function test1(){
}
function test2(){
}
}
由于php是弱类型语言,你只要清楚$lnode和$rnode的类型是node,赋值时一定要把node类型的左右节点赋给对应的就可以了。
$node0=new node();
$node0->per = 49;
$node1=new node();
$node1->per = 20;
$node2=new node();
$node2->per = 29;
$node0->lnode = $node1;
$node0->rnode = $node2;
------解决方案--------------------
这样写
$v) { //初始化
$t[] = array('w' => $v, 'v' => $v); //用值作为权重
}
huffmantree($t);
echo dlr($t), php_eol;
/* 哈夫曼算法 */
function huffmantree(&$f) {
while(count($f) > 1) {
$r = array();
foreach($f as $item) $r[] = $item['w'];
array_multisort($r, $f);
$t = array('w' => $f[0]['w']+$f[1]['w'], 'l' => $f[0], 'r' => $f[1]);
unset($f[0]);
unset($f[1]);
$f[] = $t;
}
$f = current($f);
}
/* 前序遍历 */
function dlr($f, $deep=0) {
echo str_repeat( , $deep) .'+- ' . $f['w'] . php_eol;//打印权重
if(isset($f['l'])) dlr($f['l'], $deep+1);
if(isset($f['r'])) dlr($f['r'], $deep+1);
}

+- 49
   +- 20
      +- 10
      +- 10
         +- 4
         +- 6
   +- 29
      +- 12
      +- 17
         +- 8
         +- 9
其它类似信息

推荐信息