Understanding the Problem
We are given a binary tree, and our task is to perform a preorder traversal iteratively. In preorder traversal, we visit the nodes in the order: root → left → right.
Normally, recursion is used for tree traversal, but here we want to do it without recursion, using a stack
to simulate the recursive behavior. We must carefully push the nodes in the correct order to maintain the traversal sequence.
Let’s now break this problem down step by step using an example and also see how to handle edge cases like an empty tree or skewed trees.
Step-by-Step Solution with Example
Step 1: Choose an Example
Let’s take the binary tree:
1
/ 2 3
/ 4 5
Expected preorder output: [1, 2, 4, 5, 3]
Step 2: Initialize Stack
We use a stack to help us traverse the tree. Initially, push the root node (1) to the stack.
Step 3: Traverse Using Stack
While the stack is not empty, do the following:
- Pop the top node from the stack and visit it (i.e., add to result list).
- Push the right child first (so it's visited later).
- Then push the left child (so it's visited next).
Step 4: Execution on Example
Let’s trace the steps:
- Stack = [1] → Pop 1 → Result = [1]
- Push 3, then 2 → Stack = [3, 2]
- Pop 2 → Result = [1, 2]
- Push 5, then 4 → Stack = [3, 5, 4]
- Pop 4 → Result = [1, 2, 4]
- Pop 5 → Result = [1, 2, 4, 5]
- Pop 3 → Result = [1, 2, 4, 5, 3]
Final output: [1, 2, 4, 5, 3]
Edge Cases
Case 1: Empty Tree
If the tree is empty (root is null
), return an empty list: []
. This must be checked before using the stack.
Case 2: Single Node Tree
If the tree has only one node, say 1
, the result is just [1]
.
Case 3: Left-skewed Tree
Example:
1
/
2
/
3
The output will be: [1, 2, 3]
. The stack will mimic deep recursion down the left edge.
Case 4: Right-skewed Tree
Example:
1
2
3
The output will be: [1, 2, 3]
. Only right children are added and visited in order.
Finally
Iterative preorder traversal is a great way to avoid recursion depth limits and gives us better control over the traversal order. The key trick is always pushing the right child first, so the left child is processed next. This method works on any binary tree structure—balanced, skewed, or sparse—and handles all edge cases safely with just a few lines of robust logic.
Comments
Loading comments...