VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-postorder-traversal-of-n-ary-tree/

⇱ Iterative Postorder Traversal of N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative Postorder Traversal of N-ary Tree

Last Updated : 12 Jul, 2025

Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.
Examples:
 

Input:
 1
 / | \
 3 2 4
 / \
5 6
Output: [5, 6, 3, 2, 4, 1]

Input:
 1
 / \
 2 3
Output: [2, 3, 1]


 


Approach:
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.
Pseudo Code: 
 

  • Start from the root.
  • Repeat all the steps below till either root != null OR stack is not empty. 
    1. If root != null then push root and it's an index into the stack and continues towards the left node.
    2. Pop the element from the stack and print it.
    3. Pop all the elements from stack till stack is not empty && popped node is last children of 
      it's a parent.
    4. Assign root to the next children of top of stack's node.


Below is the implementation of the above approach: 
 


Output: 
[5, 6, 3, 2, 4, 1]

 

Time complexity: O(n) where n is no of nodes in a binary tree

Auxiliary space : O(n) because using vector and stack

Comment
Article Tags: