Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.
Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1]
We have already discussed iterative post-order traversal of binary tree using one stack.We will extend that approach for the n-ary tree. The idea is very simple, for every node we have to traverse all the children of this node (from left to right) before traversing the node.
- Start from the root.
- Repeat all the steps below till either root != null OR stack is not empty.
- If root != null then push root and it’s an index into the stack and continues towards the left node.
- Pop the element from the stack and print it.
- Pop all the elements from stack till stack is not empty && popped node is last children of
it’s a parent.
- Assign root to the next children of top of stack’s node.
Below is the implementation of the above approach:
[5, 6, 3, 2, 4, 1]
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Iterative Postorder traversal | Set 3
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Find n-th node in Postorder traversal of a Binary Tree
- Postorder traversal of Binary Tree without recursion and without stack
- Find parent of given node in a Binary Tree with given postorder traversal
- Iterative Preorder Traversal of an N-ary Tree
- Iterative diagonal traversal of binary tree
- Iterative Boundary Traversal of Complete Binary tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- 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
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Iterative Preorder Traversal
- Level order traversal of Binary Tree using Morris Traversal
- Iterative Depth First Traversal of Graph
- Construct a Binary Tree from Postorder and Inorder
- Tree Traversals (Inorder, Preorder and Postorder)
- Postorder successor of a Node in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.