首页 > 其他 > 详细

Binary Tree Postorder Traversal

时间:2015-06-13 12:34:59      阅读:206      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!