php怎么实现二叉树的存储

WBOY
Release: 2016-06-13 11:06:57
Original
739 people have browsed it

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 />}
Copy after login

由于php是弱类型语言,你只要清楚$lNode和$rNode的类型是node,赋值时一定要把node类型的左右节点赋给对应的就可以了。
$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;
Copy after login

------解决方案--------------------
这样写
<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 />
Copy after login


+- 49
   +- 20
      +- 10
      +- 10
         +- 4
         +- 6
   +- 29
      +- 12
      +- 17
         +- 8
         +- 9

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template