Binary Tree Preorder Traversal
Return the preorder traversal of a binary tree iteratively using an explicit stack.
01The problem
Given the root of a binary tree, return the preorder traversal of its nodes' values. While recursion is trivial, interviewers specifically ask for an iterative solution using an explicit stack.
1
/ 2 3
/ \ 4 5 6
Preorder: [1, 2, 4, 5, 3, 6]Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
02How to spot it
- "Preorder traversal" / "Node -> Left -> Right": The parent node must be processed before either of its children.
- "Iterative follow-up": Simulating system recursion requires an explicit LIFO
Deque<TreeNode>. - Key stack ordering: To visit
leftbeforeright, pushrightfirst andleftsecond soleftpops first!
03Pseudocode
stack = [root]
while stack not empty:
n = pop()
visit n
push n.right (if any)
push n.left (if any)04Watch it work
current node
done
stack (LIFO)
preorder traversal
status
start
Initialize iterative preorder traversal. Push root onto stack.
Pseudocode
- stack = [root]
- while stack not empty:
- n = pop()
- visit n
- push n.right (if any)
- push n.left (if any)
Variables
- root
- 1
05Step-by-step dry run
We trace the algorithm on tree [1, 2, 3, 4, 5, null, 6]:
| Step | Stack state | Popped node | Action | Traversal output |
|---|---|---|---|---|
| Init | [1] | - | Push root | [] |
| 1 | [] | 1 | Visit 1; push right child 3, then left child 2 | [1] |
| 2 | [3, 2] | 2 | Visit 2; push right child 5, then left child 4 | [1, 2] |
| 3 | [3, 5, 4] | 4 | Visit 4 (leaf: no children to push) | [1, 2, 4] |
| 4 | [3, 5] | 5 | Visit 5 (leaf: no children to push) | [1, 2, 4, 5] |
| 5 | [3] | 3 | Visit 3; push right child 6 | [1, 2, 4, 5, 3] |
| 6 | [6] | 6 | Visit 6 (leaf: stack empty) | [1, 2, 4, 5, 3, 6] |
06Java solution
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public static List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null) {
stack.push(root);
}
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
out.add(n.val);
if (n.right != null) {
stack.push(n.right);
}
if (n.left != null) {
stack.push(n.left);
}
}
return out;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, null, new TreeNode(6))
);
System.out.println(preorderTraversal(root));
}
}[1, 2, 4, 5, 3, 6]
07Why it works
A stack follows Last-In-First-Out (LIFO) semantics. In preorder traversal, the node is visited immediately upon popping. Because we push n.right before n.left, the left subtree root sits at the top of the stack and is popped next. This guarantees the entirety of the left subtree is processed before the right subtree begins.
08Time and space
- Time complexity:
O(n)wherenis the number of nodes in the tree. Each node is pushed and popped exactly once. - Space complexity:
O(h)wherehis the tree height (O(n)worst case for skewed trees,O(log n)for balanced trees) to store nodes on the stack.
09Edge cases
- Empty tree (
root == null): Guardif (root != null)ensures empty list[]is returned immediately without exceptions. - Single node: Pops root, pushes no children, returns
[val]. - Left-skewed or right-skewed tree: Stack behaves linearly without failing or recursing too deeply into stack overflow.
10Common mistakes
- Pushing left before right: Pushing
leftfirst causesrightto be on top, which traverses right before left (mirrored preorder). Always pushrightfirst soleftpops first. - Using
java.util.Stack: Prefer modernArrayDeque<TreeNode>over legacy synchronizedStack.
11Other approaches
- Recursive DFS: Trivial 4-line recursive helper. Uses system stack space
O(h). - Morris Traversal: Uses temporary threaded pointers from inorder predecessors to traverse in
O(n)time andO(1)auxiliary space without a stack.
12In the interview
- Opening line: "I will use an explicit LIFO stack to simulate preorder recursion. Because left must be visited before right, I push right child first, then left."
- Follow-up: "How would you do this in
O(1)auxiliary memory?" Mention Morris traversal using threaded binary tree pointers.
13Quiz
What is the stack order when visiting node 1 with left child 2 and right child 3 in iterative preorder traversal?
- (Recommended) Push 3, then push 2, so 2 is on top and pops next
- Push 2, then push 3, so 3 is on top and pops next
- Push 1, pop 1, push both into a FIFO queue
- Recurse into right child before visiting 1
Answer: Push 3, then push 2, so 2 is on top and pops next. Because stack is LIFO, pushing right first ensures left pops first.
14Solve it yourself
Open LeetCode #144 and submit the iterative stack implementation.