Output: 10 7 1 6 10 6 5 8 Explanation: Postorder traversal (Left->Right->Root) of the tree is 10 7 1 6 10 6 5 8 .
Approach:
The idea is to push reverse Postorder traversal to a stack. Once we have the reversed postorder traversal in a stack, we can just pop all items one by one from the stack and print them; this order of printing will be in postorder because of the LIFO property of stacks. Now the question is, how to get reversed postorder elements in a stack - the second stack is used for this purpose. For example, in the following tree, we need to get 1, 3, 7, 6, 2, 5, 4 in a stack. If we take a closer look at this sequence, we can observe that this sequence is very similar to the preorder traversal. The only difference is that the right child is visited before left child, and therefore the sequence is “root right left” instead of “root left right”. So, we can do something like iterative preorder traversal with the following differences: a) Instead of printing an item, we push it to a stack. b) We push the left subtree before the right subtree.
Follow the steps below to solve the problem:
Push root to first stack.
Loop until first stack is not empty
Pop a node from first stack and push it to second stack
Push left and right children of the popped node to first stack
Following are the steps to print Postorder traversal of the above tree using two stacks:
1. Push 1 to first stack First stack: 1 Second stack: empty
2. Pop 1 from first stack and push it to second stack. Push left and right children of 1 to first stack First stack: 2, 3 Second stack: 1
3. Pop 3 from first stack and push it to second stack. Push left and right children of 3 to first stack First stack: 2, 6, 7 Second stack: 1, 3
4. Pop 7 from first stack and push it to second stack. First stack: 2, 6 Second stack: 1, 3, 7
5. Pop 6 from first stack and push it to second stack. First stack: 2 Second stack: 1, 3, 7, 6
6. Pop 2 from first stack and push it to second stack. Push left and right children of 2 to first stack First stack: 4, 5 Second stack: 1, 3, 7, 6, 2
7. Pop 5 from first stack and push it to second stack. First stack: 4 Second stack: 1, 3, 7, 6, 2, 5
8. Pop 4 from first stack and push it to second stack. First stack: Empty Second stack: 1, 3, 7, 6, 2, 5, 4
The algorithm stops here since there are no more items in the first stack. Observe that the contents of second stack are in postorder manner. Print them.
Below is the implementation of the above approach:
Output
4 5 2 3 1
Time complexity: O(n), since the algorithm processes each node exactly twice (once when pushed to s1 and once when popped from s2), where n is the number of nodes. Auxiliary space: O(n), due to the two stacks, each holding up to n nodes at different points in the traversal.