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].
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null)
return list;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack1.push(root);
while(!stack1.isEmpty()) {
TreeNode current = stack1.pop();
stack2.push(current);
if(current.left != null)
stack1.push(current.left);
if(current.right!= null)
stack1.push(current.right);
}
while(!stack2.isEmpty())
list.add(stack2.pop().val);
return list;
}
}