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?
Check for coding below in detail:
/*
Key to Solve: Stack1, Stack2(reverse order of stack1)
PostOrder: Left -> right -> root
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> out =new ArrayList<Integer>();
if(root==null) return out;
Stack<TreeNode> stack1=new Stack<TreeNode>();
Stack<TreeNode> stack2=new Stack<TreeNode>();
stack1.push(root);
while(!stack1.isEmpty()){
root=stack1.pop();
//push into stack2 for reversing
stack2.push(root);
//base of LIFO
if(root.left!=null) stack1.push(root.left);
if(root.right!=null) stack1.push(root.right);
}
while(!stack2.isEmpty()){
out.add(stack2.pop().val);
}
return out;
}
}