码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Postorder Traversal

时间:2015-06-13 12:36:30      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

http://bookshadow.com/weblog/2015/01/19/leetcode-binary-tree-postorder-traversal/

http://bookshadow.com/weblog/2015/01/19/binary-tree-post-order-traversal/

记不住啊总,不如试试双栈法,借用如上链接提示,反向preorder

 

要注意压入栈的时候子节点左右顺序

public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(root==null) return res;
        Stack<TreeNode> st = new Stack<TreeNode>();
        Stack<TreeNode> out= new Stack<TreeNode>();
        st.push(root);
        while(!st.isEmpty()){
            TreeNode n= st.pop();
            out.push(n);
            if(n.left!=null){
                st.push(n.left);
            }
            if(n.right!=null){
                st.push(n.right);
            }
        }
        while(!out.isEmpty()){
            TreeNode o = out.pop();
            res.add(o.val);
        }
        return res;
    }
}

 

Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4573232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!