|
本文实例讲述了PHP完全二叉树定义与实现方法。分享给大家供大家参考,具体如下:
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
PHP代码实现(暂时实现添加节点、层次遍历节点,删除节点后续更新)
value)){
return $node;
}else{
if(empty($node->leftNode->value)){
return $node->leftNode;
}else if(empty($node->rightNode->value)){
return $node->rightNode;
}else{
if(empty($parent) || $node->value == $parent->rightNode->value){
return findEmpytNode($node->leftNode, $node);
}else{
return findEmpytNode($parent->rightNode, $node);
}
}
}
}
/* 添加节点 */
function addNode($node, $value){
$emptyNode = findEmpytNode($node);
setNode($emptyNode, $value);
}
/* 设置节点 */
function setNode($node, $value){
$node->value = $value;
$node->leftNode = new Node();
$node->rightNode = new Node();
}
/* 打印 */
function printTree($node, $parent = null){
if(empty($node->value)) return ;
echo $node->leftNode->value;
echo $node->rightNode->value;
if(empty($parent) || $node->value == $parent->rightNode->value){
printTree($node->leftNode, $node);
}else{
printTree($parent->rightNode, $node);
}
}
$head = new Node();
setNode($head, 1);
addNode($head, 2);
addNode($head, 3);
addNode($head, 4);
addNode($head, 5);
addNode($head, 6);
printTree($head);
|
|