Created
March 25, 2019 04:20
-
-
Save aqd14/ea21daa1043bb19ccd7829d1f97df2ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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