![]() |
VOOZH | about |
We have seen different ways of performing postorder traversal on Binary Trees.
Here is another way of performing the postorder traversal on a Binary Tree iteratively using a single stack.
Consider the Below Terminologies for an extra field in the stack.
0 - Left element
1 - Right element
2 - Node element
Following is the detailed algorithm:
Take a Stack and perform the below operations:
1) Insert a pair of the root node as (node, 0).
2) Pop the top element to get the pair
(Let a = node and b be the variable)
If b is equal to 0:
Push another pair as (node, 1) and
Push the left child as (node->left, 0)
Repeat Step 2
Else If b is equal to 1:
Push another pair as (node, 2) and
Push right child of node as (node->right, 0)
Repeat Step 2
Else If b is equal to 2:
Print(node->data)
3) Repeat the above steps while stack is not empty
Consider the Below Binary Tree with just 3 nodes:
👁 ImageIllustration:
1) Push(a, 0)
Stack - (a, 0)
2) top = (a, 0)
Push(a, 1)
Push(b, 0)
Stack - (b, 0)
(a, 1)
3) top = (b, 0)
Push(b, 1)
Stack - (b, 1)
(a, 1)
4) top = (b, 1)
Push(b, 2)
Stack - (b, 2)
(a, 1)
5) top = (b, 2)
print(b)
Stack -(a, 1)
6) top = (a, 1)
push(a, 2)
push(c, 0)
Stack - (c, 0)
(a, 2)
7) top = (c, 0)
push(c, 1)
Stack - (c, 1)
(a, 2)
8) top = (c, 1)
push(c, 2)
Stack - (c, 2)
(a, 2)
9) top = (c, 2)
print(c)
Stack - (a, 2)
10) top = (a, 2)
print(a)
Stack - empty()
Below is the implementation of the above approach:
4 5 2 3 1
Time Complexity: O(n), since each node is visited exactly once, where n is the number of nodes in the tree.
Auxiliary Space: O(n), due to the stack storing tuple for each node, where n is the number of nodes in the tree.