leedcode做题总结,题目Binary Tree Postorder Traversal-------- 2013/11/07

来源:互联网 发布:淘宝专享服务 编辑:程序博客网 时间:2024/06/05 15:59

递归的方法就不提了,太简单了,非递归的方法着实想了半天,先序和中序都可以用栈深度优先历遍搞定,但是后续就比较麻烦了。


由于访问要从根节点开始,我们可以用后序历遍相反的顺序访问,然后把值从后往前加入到list中,这样从前往后就是后序历遍的了。

在访问完父节点后将左右节点依次入栈,这样出栈顺序刚好相反。


public List<Integer> postorderTraversal(TreeNode root) {        LinkedList<Integer> l = new LinkedList<Integer>();        Stack<TreeNode> s = new Stack<TreeNode>();        if(root==null)return l;        s.push(root);        while (!s.isEmpty()){            TreeNode n = s.pop();            l.addFirst(n.val);            if(n.left!=null)s.push(n.left);            if(n.right!=null)s.push(n.right);        }        return l;    }


Update 2015/08/18: 后续其实就是反向的先序(先right在left)然后从后往前插入链表,在lintcode里要求返回ArrayList,虽然我觉得LinkedList是个更好的选择,ArrayList没有addFirst方法,使用add(index, val)代替

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: The root of binary tree.     * @return: Postorder in ArrayList which contains node values.     */    public ArrayList<Integer> postorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> res = new ArrayList<Integer>();        Stack<TreeNode> stack = new Stack<>();        while (root != null || stack.size() != 0){            if (root != null){                res.add(0, root.val);                stack.push(root);                root = root.right;            } else {                root = stack.pop().left;            }        }        return res;    }}


0 0
原创粉丝点击