本文实例讲述了PHP基于非递归算法实现先序、中序及后序遍历二叉树操作。分享给大家供大家参考,具体如下:
概述:
二叉树遍历原理如下:
针对上图所示二叉树遍历:
1. 前序遍历:先遍历根结点,然后遍历左子树,最后遍历右子树。
ABDHECFG
2.中序遍历:先遍历左子树,然后遍历根结点,最后遍历右子树。
HDBEAFCG
3.后序遍历:先遍历左子树,然后遍历右子树,最后遍历根节点。
HDEBFGCA
实现方法:
先序遍历:利用栈先进后出的特性,先访问根节点,再把右子树压入,再压入左子树。这样取出的时候是先取出左子树,最后取出右子树。
- function preorder($root){
- $stack = array();
- array_push($stack, $root);
- while(!empty($stack)){
- $center_node = array_pop($stack);
- echo $center_node->value; // 根节点
- if($center_node->right != null)
- array_push($stack, $center_node->right); // 压入右子树
- if($center_node->left != null)
- array_push($stack, $center_node->left); // 压入左子树
- }
- }
中序:需要从下向上遍历,所以先把左子树压入栈,然后逐个访问根节点和右子树。
- function inorder($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->left;
- }
- $center_node = array_pop($stack);
- echo $center_node->value;
- $center_node = $center_node->right;
- }
- }
后序:先把根节点存起来,然后依次储存左子树和右子树。然后输出。
- function tailorder($root){
- $stack = array();
- $outstack = array();
- array_push($$stack, $root);
- while($empty($stack)){
- $center_node = array_pop($stack);
- array_push($outstack, $center_node);
- if($center_node->right != null)
- array_push($stack, $center_node->right);
- if($center_node->left != null)
- array_push($stack, $center_node->left);
- }
- while($empty($outstack)){
- $center_node = array_pop($outstack);
- echo $center_node->value;
- }
- }
希望本文所述对大家PHP程序设计有所帮助。