Problem Description
Given the root of a binary tree, return the postorder traversal of its nodes' values. The postorder traversal visits the left subtree, the right subtree, and then the node itself. While the recursive solution is straightforward, the challenge here is to implement it iteratively.
Key Insights
- Use an iterative approach to avoid recursion.
- A two-stack strategy can reverse the order of node processing to simulate postorder traversal.
- One stack can be used too, though the two-stack method is intuitive: first stack for processing nodes, second stack to reverse the order.
- Edge case: if the tree is empty, return an empty list.
Space and Time Complexity
Time Complexity: O(n) – Each node is processed once. Space Complexity: O(n) – In worst case, both stacks can contain up to all the nodes in the tree.
Solution
The solution uses a two-stack approach. The first stack is used for traversing the tree in a modified pre-order (root, right, left) such that when nodes are transferred into the second stack, they will be in the postorder (left, right, root) order. Finally, the values in the second stack are collected and returned as the result.