Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递归后序遍历
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root==null)
return ret;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
TreeNode cur = null;
stack.push(root);
while(!stack.isEmpty()){
cur = stack.peek();
if((cur.left==null&&cur.right==null)||(pre!=null&&(pre==cur.left||pre==cur.right))){
ret.add(cur.val);
stack.pop();
pre=cur;
}else {
if(cur.right!=null)
stack.push(cur.right);
if(cur.left!=null)
stack.push(cur.left);
}
}
return ret;
}
}