Understanding the Problem
In postorder traversal of a binary tree, the nodes are visited in the order: left subtree → right subtree → root. This is typically done using recursion, but in this solution, we want to implement it iteratively.
The challenge is that postorder is the only traversal where the root is visited after both children, which makes an iterative approach less straightforward compared to preorder or inorder traversals. We need a way to ensure that nodes are processed after their left and right subtrees have been fully traversed.
We will walk through this step-by-step using a concrete example and build up the solution using two stacks to simulate the recursive behavior.
Step-by-Step Solution with Example
Step 1: Choose an Example
Let's take this binary tree as our example:
1
/ 2 3
/ 4 5 6
Expected postorder traversal: [4, 5, 2, 6, 3, 1]
Step 2: Initialize Two Stacks
We use stack1 for traversal and stack2 to store nodes in postorder reverse format.
Push the root (1) to stack1.
Step 3: Traverse Using stack1
While stack1 is not empty:
- Pop a node from
stack1 and push it to stack2.
- Push the left child of the node (if it exists) to
stack1.
- Push the right child (if it exists) to
stack1.
This effectively processes root-right-left order and stores them in stack2.
Step 4: Collect Postorder from stack2
Finally, pop all elements from stack2 to get them in left-right-root (postorder) order.
From the above tree, the steps will look like:
stack1: [1] → pop 1 → push to stack2
- push 2, push 3 →
stack1: [2, 3]
- pop 3 → push to
stack2 → push 6 → stack1: [2, 6]
- pop 6 → push to
stack2
- pop 2 → push to
stack2 → push 4, 5 → stack1: [4, 5]
- pop 5 → push to
stack2, pop 4 → push to stack2
Now stack2 contains: [1, 3, 6, 2, 5, 4]. Reversing gives us the postorder: [4, 5, 2, 6, 3, 1]
Edge Cases
Case 1: Empty Tree
If the root is null, simply return an empty list as there are no nodes to traverse.
Case 2: Single Node Tree
If the tree has only one node, that node is both the root and the only node. The postorder traversal will just return that node.
Case 3: Only Left or Right Subtree
For a skewed tree (e.g., [1,null,2,3]), traversal must still follow left-right-root logic. The iterative two-stack method ensures the correct order even when one side is missing.
Case 4: Full Binary Tree
In trees where every node has 0 or 2 children, the traversal will still work seamlessly, because both children are always processed before the root is added to the result.
Finally
Iterative postorder traversal can be tricky because of the requirement to process the root after both children. Using two stacks simplifies this by reversing a modified preorder traversal. This method is reliable and handles all edge cases, including skewed and full trees.
Always remember: stack2 will give you the correct postorder traversal when you reverse the root-right-left order pushed into it.