Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 6, 2015 04:10
Show Gist options
  • Save kanrourou/f7f4d46b2285539cc717 to your computer and use it in GitHub Desktop.
Save kanrourou/f7f4d46b2285539cc717 to your computer and use it in GitHub Desktop.
/**
* 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;
TreeNode sentinel = new TreeNode(0);
sentinel.left = root;
TreeNode curr = sentinel;
while (curr != null) {
if (curr.left == null) {
curr = curr.right;
} else {
TreeNode temp = curr.left;
while (temp.right != null && temp.right != curr)
temp = temp.right;
if (temp.right == null) {
temp.right = curr;
curr = curr.left;
} else {
collect(res, curr.left, temp);
temp.right = null;
curr = curr.right;
}
}
}
return res;
}
private void collect(List<Integer> res, TreeNode from, TreeNode to) {
reverse(from, to);
TreeNode curr = to;
while (curr != from) {
res.add(curr.val);
curr = curr.right;
}
res.add(from.val);
reverse(to, from);
}
private void reverse(TreeNode from, TreeNode to) {
TreeNode a = from, b = from.right;
while (a != to) {
TreeNode c = b.right;
b.right = a;
a = b;
b = c;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment