《2023年php二叉树遍历代码大全.docx》由会员分享,可在线阅读,更多相关《2023年php二叉树遍历代码大全.docx(6页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、2023年php二叉树遍历代码大全 无论是身处学校还是步入社会,大家都尝试过写作吧,借助写作也可以提高我们的语言组织实力。范文怎么写才能发挥它最大的作用呢?下面是我帮大家整理的优质范文,仅供参考,大家一起来看看吧。 php二叉树遍历代码篇一 本文主要介绍了php实现的二叉树遍历算法,结合详细实例形式分析了php针对二叉树的常用前序、中序及后序遍历算法实现技巧,须要的挚友可以参考一下!想了解更多相关信息请持续关注我们应届毕业生考试网! <?php class node public $value; public $child_left; public $child_right; final
2、 class ergodic /前序遍历:先访问根节点,再遍历左子树,最终遍历右子树;并且在遍历左右子树时,仍需先遍历根节点,然后访问左子树,最终遍历右子树 public static function preorder($root) $stack = array(); array_push($stack, $root); while(!empty($stack) $center_node = array_pop($stack); echo $center_node->value . ; /先把右子树节点入栈,以确保左子树节点先出栈 if($center_node->child_r
3、ight != 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;
4、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; /后序遍历:先遍历左子树,然后遍历右子树,最终访问根节点;同样,在遍历左
5、右子树的时候同样要先遍历左子树,然后遍历右子树,最终访问根节点 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 (
6、$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 =
7、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->v
8、alue = 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 <br/> /中序遍历 ergodic:midorder($a); /结果是: h d i b g a e c f echo <br/> /后序遍历 ergodic:endorder($a); /结果是: h i d g b e f c a s(content_relate);