|
本文实例讲述了php实现的二叉树遍历算法。分享给大家供大家参考,具体如下:
今天使用php来实现二叉树的遍历
创建的二叉树如下图所示
php代码如下所示:
value . ' ';
//先把右子树节点入栈,以确保左子树节点先出栈
if($center_node->child_right != null) array_push($stack, $center_node->child_right);
if($center_node->child_left != null) array_push($stack, $center_node->child_left);
}
}
//中序遍历:先遍历左子树、然后访问根节点,最后遍历右子树;并且在遍历左右子树的时候。仍然是先遍历左子树,然后访问根节点,最后遍历右子树
public static function midOrder($root){
$stack = array();
$center_node = $root;
while (!empty($stack) || $center_node != null) {
while ($center_node != null) {
array_push($stack, $center_node);
$center_node = $center_node->child_left;
}
$center_node = array_pop($stack);
echo $center_node->value . ' ';
$center_node = $center_node->child_right;
}
}
//后序遍历:先遍历左子树,然后遍历右子树,最后访问根节点;同样,在遍历左右子树的时候同样要先遍历左子树,然后遍历右子树,最后访问根节点
public static function endOrder($root){
$push_stack = array();
$visit_stack = array();
array_push($push_stack, $root);
while (!empty($push_stack)) {
$center_node = array_pop($push_stack);
array_push($visit_stack, $center_node);
//左子树节点先入$pushstack的栈,确保在$visitstack中先出栈
if ($center_node->child_left != null) array_push($push_stack, $center_node->child_left);
if ($center_node->child_right != null) array_push($push_stack, $center_node->child_right);
}
while (!empty($visit_stack)) {
$center_node = array_pop($visit_stack);
echo $center_node->value . ' ';
}
}
}
//创建二叉树
$a = new Node();
$b = new Node();
$c = new Node();
$d = new Node();
$e = new Node();
$f = new Node();
$g = new Node();
$h = new Node();
$i = new Node();
$a->value = 'A';
$b->value = 'B';
$c->value = 'C';
$d->value = 'D';
$e->value = 'E';
$f->value = 'F';
$g->value = 'G';
$h->value = 'H';
$i->value = 'I';
$a->child_left = $b;
$a->child_right = $c;
$b->child_left = $d;
$b->child_right = $g;
$c->child_left = $e;
$c->child_right = $f;
$d->child_left = $h;
$d->child_right = $i;
//前序遍历
Ergodic::preOrder($a); //结果是:A B D H I G C E F
echo '
';
//中序遍历
Ergodic::midOrder($a); //结果是: H D I B G A E C F
echo '
';
//后序遍历
Ergodic::endOrder($a); //结果是: H I D G B E F C A
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:PHP实现二叉树的深度优先与广度优先遍历方法PHP实现的线索二叉树及二叉树遍历方法详解PHP构造二叉树算法示例PHP完全二叉树定义与实现方法示例PHP实现绘制二叉树图形显示功能详解【包括二叉搜索树、平衡树及红黑树】PHP实现判断二叉树是否对称的方法PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例PHP实现按之字形顺序打印二叉树的方法PHP获取二叉树镜像的方法PHP实现从上往下打印二叉树的方法
|
|