/*
** This is problem can be solved in a very smart way.
** The key point here is if you use a stack to do DFS
** (Left-to-right), the order of visiting is preorder.
** But, if you do in the opposite way, it will generate
** the opposite result of postorder traversal.
**
** Preorder, stack push right first, then left
** PostOrder, stack push left first, then right, after
** finish the loop, reverse the result.
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null) return ans;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode curr = stack.pop();
ans.add(curr.val);
if (curr.left != null)
stack.push(curr.left);
if (curr.right != null)
stack.push(curr.right);
}
Collections.reverse(ans);
return ans;
}
}
Tuesday, July 1, 2014
LeetCode: Binary Tree PostOrder Traversal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment