二叉树三种遍历方式的非递归实现

1、二叉树的先序遍历。

节点->左孩子->右孩子

用递归很容易解决,但是会遇到内存溢出情况。用栈可以解决找个问题。

根据前序遍历访问的顺序,优先访问根结点,然后再分别访问左孩子和右孩子。即对于任一结点,其可看做是根结点,因此可以直接访问,访问完之后,若其左孩子不为空,按相同规则访问它的左子树;当访问其左子树时,再访问它的右子树。因此其处理过程如下:

  对于任一结点P:

     1)访问结点P,并将结点P入栈;

     2)判断结点P的左孩子是否为空,若为空,则取栈顶结点并进行出栈操作,并将栈顶结点的右孩子置为当前的结点P,循环至1);若不为空,则将P的左孩子置为当前的结点P;

     3)直到P为NULL并且栈为空,则遍历结束。

 1    public void xianxu(TreeNode root){
 2         Stack<TreeNode> stack = new Stack<>();
 3         TreeNode p = root;
 4         while ( !stack.isEmpty() ){
 5             while ( p != null ){
 6                 System.out.println(p.val);
 7                 stack.push(p);
 8                 p = p.left;
 9             }
10             if ( !stack.isEmpty() ){
11                 p = stack.pop();
12                 p = p.right;
13             }
14         }
15     }

2、二叉树中序遍历

根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一根结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问,然后按相同的规则访问其右子树。因此其处理过程如下:

  对于任一结点P,

   1)若其左孩子不为空,则将P入栈并将P的左孩子置为当前的P,然后对当前结点P再进行相同的处理;

   2)若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将当前的P置为栈顶结点的右孩子;

   3)直到P为NULL并且栈为空则遍历结束。

 1     public void zhongxu(TreeNode root){
 2         Stack<TreeNode> stack = new Stack<>();
 3         TreeNode t = root;
 4         while ( !stack.isEmpty() || t != null ){
 5             while ( t != null ){
 6                 stack.push(t);
 7                 t = t.left;
 8             }
 9             if ( !stack.isEmpty() ){
10                 t = stack.pop();
11                 System.out.println(t.val);
12                 t = t.right;
13             }
14         }
15     }

3、二叉树后序遍历

要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。

1)如果P不存在左孩子和右孩子,则可以直接访问它;

2)或者P存 在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。

3)若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了 每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

根据上面的思路,我们需要一个指针来记录之前cur节点前面访问的节点。

 1    public void houxu(TreeNode root){
 2         Stack<TreeNode> stack = new Stack<>();
 3         TreeNode cur; //指向当前节点
 4         TreeNode pre=null; //保存当前节点前一次访问的节点
 5         stack.push(root);
 6         while ( !stack.isEmpty() ){
 7             cur = stack.peek();
 8             //精髓。pre指针记录了cur的孩子是否被访问。
 9             //只有当节点是叶子节点,或者它的左右孩子已经被输出之后,才能输出cur节点。
10             if ( (cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right) ) ){
11                 System.out.println(cur.val);
12                 stack.pop();
13                 pre = cur;
14             }
15             else {
16                 if ( cur.right != null ) stack.push(cur.right);
17                 if ( cur.left != null ) stack.push(cur.left);
18             }
19         }
20     }

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9398848.html