Understanding the Problem
Inorder traversal is a common way to visit all the nodes in a binary tree. The order of traversal is: Left subtree → Node → Right subtree. When done recursively, it’s straightforward. But when we try to do it iteratively, we need to simulate the call stack manually using a data structure — typically a stack.
Our goal is to traverse the binary tree in inorder sequence using an iterative approach, even in complex or edge structures like skewed trees or empty trees.
Step-by-Step Solution with Example
Step 1: Use a Stack to Simulate Recursion
We use a stack to keep track of nodes while going left. This mimics the call stack of a recursive solution. We keep pushing nodes onto the stack as we go left.
Step 2: Start from the Root
Initialize a stack, and set the current pointer to the root. As long as the current node is not null, push it onto the stack and move left.
Step 3: Process the Leftmost Node
Once current becomes null, we pop a node from the stack — this is the node we visit next. Add its value to the result list.
Step 4: Move to the Right Subtree
After visiting a node, move the current pointer to its right child. Repeat the process — push all left children of the new current onto the stack.
Step 5: Loop Until Done
Repeat steps 2–4 until the stack is empty and the current pointer is null. This ensures all nodes are visited in inorder.
Example Walkthrough
Given binary tree:
1
/ 2 3
/ 4 5
Inorder traversal: [4, 2, 5, 1, 3]
Steps:
- Start at root (1), push to stack → go left to 2 → push → go left to 4 → push → no more left.
- Pop 4, visit it → move to null → pop 2, visit it → move to right (5)
- Push 5 → no left → pop and visit 5 → move to null
- Pop 1, visit it → move to right (3) → push → no left → pop and visit
Final output: [4, 2, 5, 1, 3]
Edge Cases
Left-Skewed Tree
Example: 4 → 3 → 2 → 1 (all nodes only have left children). We keep pushing nodes until we reach null, then pop and visit nodes bottom-up. Result is: [1, 2, 3, 4]
Right-Skewed Tree
Example: 1 → 2 → 3 → 4 (only right children). There are no left nodes to push, so we visit the node directly and move to the right. Result is: [1, 2, 3, 4]
Single Node Tree
Only root node exists. We visit it, and there are no left or right children. Output is simply: [node.val]
Empty Tree
If the root is null, then there are no nodes to traverse. Return an empty list. This must be handled explicitly to avoid null reference errors.
Finally
Inorder traversal using iteration may seem tricky at first, but with a stack and a pointer to current node, it becomes intuitive. Always remember: push while going left, pop and visit when you hit null, then move right. Understanding the structure of the tree and edge cases ensures a robust and error-free solution.