Skip to content

Instantly share code, notes, and snippets.

@aqd14
Created March 25, 2019 04:20
Show Gist options
  • Save aqd14/ea21daa1043bb19ccd7829d1f97df2ac to your computer and use it in GitHub Desktop.
Save aqd14/ea21daa1043bb19ccd7829d1f97df2ac to your computer and use it in GitHub Desktop.
// node.left -> node.right -> node
public void postorder(TreeNode root) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
stack1.push(root);
TreeNode current;
while (!stack1.empty() || current != null) {
current = stack1.pop();
stack2.push(current);
if (current.left != null) {
stack1.push(current.left);
}
if (current.right != null) {
stack1.push(current.right);
}
}
while (!stack2.empty()) {
visit(stack2.pop());
}
}
// Using Deque in Java
public void postorder(TreeNode root) {
Deque<TreeNode> deque = new Deque<>();
TreeNode current = root;
while (!deque.empty() || current != null) {
if (current != null) {
deque.addFirst(current);
current = current.left;
} else {
current = deque.pop();
visit(current);
current = current.right;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment