Binary Tree Preorder Traversal (Iterative)
Binary Tree Preorder Traversal (Iterative) is a easy trees & bst problem solved with the recursion pattern.
The best approach, iterative (stack), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, from recursive (reference) up.
Problem
Return the preorder traversal of a binary tree iteratively, using an explicit stack.
Examples
Example 1
- Input
root = [5, 3, 8, 1, 4]- Output
[5, 3, 1, 4, 8]
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to100nodes. - Solve it without recursion.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursive (reference) | O(n) | O(h) |
| Iterative (stack) | O(n) | O(h) |
1Recursive (reference)
O(n)O(h)Node, left, right with the call stack.
- add; preorder(left); preorder(right).
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
go(root, out);
return out;
}
private void go(TreeNode n, List<Integer> out) {
if (n == null) return;
out.add(n.val);
go(n.left, out);
go(n.right, out);
}
}2Iterative (stack)
O(n)O(h)Pop a node and record it immediately. Push right then left, so the left subtree is fully processed before the right.
- Push root.
- Pop, add, push right (if any), push left (if any).
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> st = new ArrayDeque<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode n = st.pop();
out.add(n.val);
if (n.right != null) st.push(n.right);
if (n.left != null) st.push(n.left);
}
return out;
}
}Edge cases to test
- Empty tree
Hints
Hint 1
A stack is last-in-first-out, so push the right child before the left one.
FAQ
What is the best time complexity for Binary Tree Preorder Traversal (Iterative)?
Iterative (stack) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Preorder Traversal (Iterative) use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Binary Tree Preorder Traversal (Iterative)?
Yes. Recursive (reference) takes O(n) time and O(h) space. Node, left, right with the call stack.
Which edge cases should I test for Binary Tree Preorder Traversal (Iterative)?
Empty tree.