概述:
二叉树遍历原理如下:
针对上图所示二叉树遍历:
1. 前序遍历:先遍历根结点,然后遍历左子树,最后遍历右子树。
ABDHECFG
2.中序遍历:先遍历左子树,然后遍历根结点,最后遍历右子树。
HDBEAFCG
3.后序遍历:先遍历左子树,然后遍历右子树,最后遍历根节点。
HDEBFGCA
实现方法:
先序遍历:利用栈先进后出的特性,先访问根节点,再把右子树压入,再压入左子树。这样取出的时候是先取出左子树,最后取出右子树。
1
2
3
4
5
6
7
8
9
10
11
12
|
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); // 压入左子树 } } |
中序:需要从下向上遍历,所以先把左子树压入栈,然后逐个访问根节点和右子树。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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; } } |
后序:先把根节点存起来,然后依次储存左子树和右子树。然后输出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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; } } |
原文链接:http://blog.csdn.net/acingdreamer/article/details/70377864
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容