您的位置:首页 > 其它

Binary Tree Postorder Traversal

2015-06-13 11:44 190 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: