二叉树后序遍历非递归实现

来源:互联网 发布:最强淘宝系统虾兵蟹将 编辑:程序博客网 时间:2024/05/21 18:49

二叉树的先序,中序遍历的非递归遍历方法比较简单,只要借助一个栈就可以很容易实现。但其后序遍历就有些复杂了,这里借鉴下面这篇文章中的后序非递归遍历算法。http://blog.csdn.net/xingzhemoluo/article/details/40898233

利用两个栈来实现后序遍历,一个栈用于存储遍历结果,另一个栈作为一个辅助栈。

/*二叉树后序非递归遍历    * 借助两个栈可以用很简单的方式实现二叉树的后序非递归遍历    * */    public static void postOrder(TreeNode root){        if (root == null){            return;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        Stack<TreeNode> output = new Stack<TreeNode>();        TreeNode p = root;        while (p != null || !stack.isEmpty()){            if (p != null){                stack.push(p);                output.push(p);                p = p.right;            }else{                p = stack.pop();                p = p.left;            }        }        while (!output.isEmpty()){            System.out.println(output.pop().val + " ");        }    }
public class TreeNode {    public int val;    public TreeNode left;    public TreeNode right;    public TreeNode(int x){        this.val = x;    }}



0 0
原创粉丝点击