LeetCode 145 Binary Tree Postorder Traversal

来源:互联网 发布:ios编程入门 编辑:程序博客网 时间:2024/04/29 10:02

二叉树的非递归后序遍历

普通认为后序遍历的非递归方式比前序和中序要难,难在什么地方呢。

首先,后序遍历的顺序是左子树-》右子树-》根节点

假如按照中序和前序的想法进行,首先用stack压入左子树的左孩子节点,直到左节点为空;那每次栈弹出的顺序肯定就是左孩子节点-》父节点。一旦父节点弹出栈,遍历完右子树之后,就无法返回了。这是我们经常卡住的地方。

public List<Integer> postorderTraversal(TreeNode root){List<Integer> list = new ArrayList<Integer>();Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode current = root;while(!stack.isEmpty()||current!=null){if(current!=null){stack.push(current);current=current.left;}else{current=stack.pop();if(current.right!=null)//如果右孩子不为空,重新入栈{    stack.push(current);}else{    list.add(current.val);    if(!stack.isEmpty()){    if(stack.peek().right==current)    {        stack.peek().right=null;    }else    {        stack.peek().left=null;    }    }} current=current.right;}}return list;}

这种方法的缺点是:破坏了树的原有结构,遍历过程相当于拆树的过程。

0 0