php如何实现二叉树的存储?
就像上面图片里面所画的一样,我怎么把那一串数字用二叉树存起来?用php实现。
求大神帮忙呀!!!!
==========初学二叉树
------解决方案--------------------
这个很简单
class node{<br /> public var $per;<br /> public var $lNode;<br /> public var $rNode;<br /> <br /> function test1(){<br /> }<br /> <br /> function test2(){<br /> }<br /> }
$node0=new node();<br /> $node0->per = 49;<br /> $node1=new node();<br /> $node1->per = 20;<br /> $node2=new node();<br /> $node2->per = 29;<br /> $node0->lNode = $node1;<br /> $node0->rNode = $node2;
<xmp><br /> <?php<br /> $s = '4 6 8 9 10 12';<br /> foreach(explode(' ', $s) as $k=>$v) { //初始化<br /> $t[] = array('w' => $v, 'v' => $v); //用值作为权重<br /> }<br /> HuffmanTree($t);<br /> echo DLR($t), PHP_EOL;<br /> <br /> /* 哈夫曼算法 */<br /> function HuffmanTree(&$F) {<br /> while(count($F) > 1) {<br /> $r = array();<br /> foreach($F as $item) $r[] = $item['w'];<br /> array_multisort($r, $F);<br /> $t = array('w' => $F[0]['w']+$F[1]['w'], 'l' => $F[0], 'r' => $F[1]);<br /> unset($F[0]);<br /> unset($F[1]);<br /> $F[] = $t;<br /> }<br /> $F = current($F);<br /> }<br /> /* 前序遍历 */<br /> function DLR($F, $deep=0) {<br /> echo str_repeat(" ", $deep) .'+- ' . $F['w'] . PHP_EOL;//打印权重<br /> if(isset($F['l'])) DLR($F['l'], $deep+1);<br /> if(isset($F['r'])) DLR($F['r'], $deep+1);<br /> }<br />