We have seen different ways of performing postorder traversal on Binary Trees.
- Post Order Traversal.
- Iterative Postorder Traversal using Two Stacks.
- Iterative Postorder Traversal using One Stack.
Here is another way of performing the postorder traversal on a Binary Tree iteratively using a single stack.
Consider the Below Terminologies:
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:
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
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Find postorder traversal of BST from preorder traversal
- Construct a BST from given postorder traversal using Stack
- Print Postorder traversal from given Inorder and Preorder traversals
- Postorder traversal of Binary Tree without recursion and without stack
- Find n-th node in Postorder traversal of a Binary Tree
- Iterative Preorder Traversal
- Iterative Depth First Traversal of Graph
- Iterative Preorder Traversal of an N-ary Tree
- Iterative diagonal traversal of binary tree
- Iterative Boundary traversal of Complete Binary tree
- Preorder from Inorder and Postorder traversals
- Postorder successor of a Node in Binary Tree
- Construct a Binary Search Tree from given postorder
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : andrew1234