Binary Tree Postorder Traversal
Source
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].
Java
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while(cur!=null){
result.add(cur.val);
stack.push(cur);
cur=cur.right;
}
while(!stack.isEmpty()){
cur = stack.pop().left;
while(cur!=null){
result.add(cur.val);
stack.push(cur);
cur=cur.right;
}
}
Collections.reverse(result);
return result;
}
}