日期:2014-05-17 浏览次数:20850 次
class node{
public var $per;
public var $lNode;
public var $rNode;
function test1(){
}
function test2(){
}
}
$node0=new node();
$node0->per = 49;
$node1=new node();
$node1->per = 20;
$node2=new node();
$node2->per = 29;
$node0->lNode = $node1;
$node0->rNode = $node2;
<xmp>
<?php
$s = '4 6 8 9 10 12';
foreach(explode(' ', $s) as $k=>$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);
}