Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 5, 2015 23:41
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null)
return res;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
stack.push(root);
while(!stack.isEmpty()) {
TreeNode curr = stack.peek();
if (isLeaf(curr) || (pre != null && (pre == curr.left || pre == curr.right))) {
res.add(stack.pop().val);
pre = curr;
}
else {
if (curr.right != null)
stack.push(curr.right);
if (curr.left != null)
stack.push(curr.left);
}
}
return res;
}
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment