Iterative Postorder Traversal of N-ary Tree

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.

Psuedo 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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

    // Node class
    static class Node {
        public int val;
        public List<Node> children = new ArrayList<Node>();
      
        // Default constructor
        public Node() {}
      
        public Node(int _val)
        {
            val = _val;
        }
      
        public Node(int _val, List<Node> _children)
        {
            val = _val;
            children = _children;
        }
    };
      
    // Helper class to push node and it's index
    // into the stack
    static class Pair {
        public Node node;
        public int childrenIndex;
        public Pair(Node _node, int _childrenIndex)
        {
            node = _node;
            childrenIndex = _childrenIndex;
        }
    }
      
    // We will keep the start index as 0, 
    // because first we always
    // process the left most children
    int currentRootIndex = 0;
    Stack<Pair> stack = new Stack<Pair>();
    ArrayList<Integer> postorderTraversal = 
                        new ArrayList<Integer>();
      
    // Function to perform iterative postorder traversal
    public ArrayList<Integer> postorder(Node root)
    {
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                  
                // Push the root and it's index 
                // into the stack
                stack.push(new Pair(root, currentRootIndex));
                currentRootIndex = 0;
      
                // If root don't have any children's that 
                // means we are already at the left most
                // node, so we will mark root as null
                if (root.children.size() >= 1) {
                    root = root.children.get(0);
                }
                else {
                    root = null;
                }
                continue;
            }
      
            // We will pop the top of the stack and
            // add it to our answer
            Pair temp = stack.pop();
            postorderTraversal.add(temp.node.val);
      
            // Repeatedly we will the pop all the 
            // elements from the stack till popped 
            // element is last children of top of
            // the stack
            while (!stack.isEmpty() && temp.childrenIndex == 
                    stack.peek().node.children.size() - 1) {
                temp = stack.pop();
                  
                postorderTraversal.add(temp.node.val);
            }
      
            // If stack is not empty, then simply assign 
            // the root to the next children of top
            // of stack's node
            if (!stack.isEmpty()) {
                root = stack.peek().node.children.get(
                                        temp.childrenIndex + 1);
                currentRootIndex = temp.childrenIndex + 1;
            }
        }
      
        return postorderTraversal;
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        GFG solution = new GFG();
        Node root = new Node(1);
      
        root.children.add(new Node(3));
        root.children.add(new Node(2));
        root.children.add(new Node(4));
      
        root.children.get(0).children.add(new Node(5));
        root.children.get(0).children.add(new Node(6));
      
        System.out.println(solution.postorder(root));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to iterative Postorder Traversal of N-ary Tree
using System;
using System.Collections.Generic;
  
class GFG
{
    // Node class
    public class Node 
    {
        public int val;
        public List<Node> children = new List<Node>();
      
        // Default constructor
        public Node() {}
      
        public Node(int _val)
        {
            val = _val;
        }
      
        public Node(int _val, List<Node> _children)
        {
            val = _val;
            children = _children;
        }
    };
      
    // Helper class to.Push node and it's index
    // into the stack
    class Pair 
    {
        public Node node;
        public int childrenIndex;
        public Pair(Node _node, int _childrenIndex)
        {
            node = _node;
            childrenIndex = _childrenIndex;
        }
    }
      
    // We will keep the start index as 0, 
    // because first we always
    // process the left most children
    int currentRootIndex = 0;
    Stack<Pair> stack = new Stack<Pair>();
    List<int> postorderTraversal = 
                        new List<int>();
      
    // Function to perform iterative postorder traversal
    public List<int> postorder(Node root)
    {
        while (root != null || stack.Count != 0) 
        {
            if (root != null)
            {
                  
                // Push the root and it's index 
                // into the stack
                stack.Push(new Pair(root, currentRootIndex));
                currentRootIndex = 0;
      
                // If root don't have any children's that 
                // means we are already at the left most
                // node, so we will mark root as null
                if (root.children.Count >= 1) 
                {
                    root = root.children[0];
                }
                else
                {
                    root = null;
                }
                continue;
            }
      
            // We will.Pop the top of the stack and
            //.Add it to our answer
            Pair temp = stack.Pop();
            postorderTraversal.Add(temp.node.val);
      
            // Repeatedly we will the.Pop all the 
            // elements from the stack till.Popped 
            // element is last children of top of
            // the stack
            while (stack.Count != 0 && temp.childrenIndex == 
                    stack.Peek().node.children.Count - 1) 
            {
                temp = stack.Pop();
                  
                postorderTraversal.Add(temp.node.val);
            }
      
            // If stack is not empty, then simply assign 
            // the root to the next children of top
            // of stack's node
            if (stack.Count != 0)
            {
                root = stack.Peek().node.children[temp.childrenIndex + 1];
                currentRootIndex = temp.childrenIndex + 1;
            }
        }
      
        return postorderTraversal;
    }
      
    // Driver Code
    public static void Main(String[] args)
    {
        GFG solution = new GFG();
        Node root = new Node(1);
      
        root.children.Add(new Node(3));
        root.children.Add(new Node(2));
        root.children.Add(new Node(4));
      
        root.children[0].children.Add(new Node(5));
        root.children[0].children.Add(new Node(6));
        Console.Write("[");
        List<int> temp = solution.postorder(root);
        int size = temp.Count;
        int count = 0;
        foreach(int v in temp)
        {
            Console.Write(v);
            count++;
            if(count < size)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

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


My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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 : princiraj1992



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.