Construct a Complete N-ary Tree from given Postorder Traversal
Last Updated : 23 Jul, 2025
Given an arrayarr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal.
A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible.
Approach: The approach to the problem is based on the following facts about the complete N-ary tree:
Say any subtree of the complete N-ary tree has a height H. So there are total H+1 levels numbered from 0 to H.
Total number of nodes in first H levels are N0 + N1 + N2 + . . . + NH-1 = (NH - 1)/(N - 1).
The maximum possible nodes in the last level is NH. So if the last level of the subtree has at least NH nodes, then total nodes in the last level of the subtree is (NH - 1)/(N - 1) + NH
The height H can be calculated as ceil[logN( M*(N-1) +1)] - 1 because N-ary complete binary tree there can have at max (NH+1 - 1)/(N - 1)] nodes
Since the given array contains the post-order traversal, the last element of the array will always be the root node. Now based on the above observation the remaining array can be partitioned into a number of subtrees of that node.
Follow the steps mentioned below to solve the problem:
The last element of the array is the root of the tree.
Now break the remaining array into subarrays which represent the total number of nodes in each subtree.
Each of these subtrees surely has a height of H-2 and based on the above observation if any subtree has more than (NH-1 - 1)/(N - 1) nodes then it has a height of H-1.
To calculate the number of nodes in subtrees follow the below cases:
If the last level has more than NH-1 nodes, then all levels in this subtree are full and the subtree has (NH-1-1)/(N-1) + NH-1 nodes.
Otherwise, the subtree will have (NH-1-1)/(N-1) + L nodes where L is the number of nodes in the last level.
L can be calculated as L = M - (NH - 1)/(N - 1).
To generate each subarray repeatedly apply the 2nd to 4th steps adjusting the size (M) and height (H) accordingly for each subtree.
Return the preorder traversal of the tree formed in this way
Follow the illustration below for a better understanding
Illustration:
Consider the example: arr[] = {5, 6, 7, 2, 8, 9, 3, 4, 1}, N = 3.
2nd step: The remaining array will be broken into subtrees. For the first subtree H = 2. 5 > 32-1 i.e., L > 3. So the last level is completely filled and the number of nodes in the first subtree = (3-1)/2 + 3 = 4 [calculated using the formulae shown above].
The first subtree contains element = {5, 6, 7, 2}. The remaining part is {8, 9, 3, 4} The root of the subtree = 2.
Now when the subtree for 5, 6, and 7 are calculated using the same method they don't have any children and are the leaf nodes themselves.
2nd step of generating the tree
3rd step: Now L is updated to 2. 2 < 3. So using the above formula, number of nodes in the second subtree is 1 + 2 = 3.
So the second subtree have elements {8, 9, 3} and the remaining part is {4} and 3 is the root of the second subtree.
3rd step of generating the tree
4th step: L = 0 now and the only element of the subtree is {4} itself.
Final structure of tree
After this step the tree is completely built.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// Node Classtemplate<typenameT>classNode{public:Node(Tdata);// Get the first child of the NodeNode*get_first_child()const;// Get the Next Sibling of The nodeNode*get_next_sibling()const;// Sets the next sibling of the nodevoidset_next_sibling(Node*node);// Sets the next child of the nodevoidset_next_child(Node*node);// Returns the data the node containsTget_data();private:Tdata;// We use the first child/next sibling representation// to represent the TreeNode*first_child;Node*next_sibling;};// Using template for generic usagetemplate<typenameT>Node<T>::Node(Tdata){first_child=NULL;next_sibling=NULL;this->data=data;}// Function to get the first childtemplate<typenameT>Node<T>*Node<T>::get_first_child()const{returnfirst_child;}// Function to get the siblingstemplate<typenameT>Node<T>*Node<T>::get_next_sibling()const{returnnext_sibling;}// Function to set next siblingtemplate<typenameT>voidNode<T>::set_next_sibling(Node<T>*node){if(next_sibling==NULL){next_sibling=node;}else{next_sibling->set_next_sibling(node);}}// Function to get the datatemplate<typenameT>TNode<T>::get_data(){returndata;}// Function to set the child node valuetemplate<typenameT>voidNode<T>::set_next_child(Node<T>*node){if(first_child==NULL){first_child=node;}else{first_child->set_next_sibling(node);}}// Function to construct the treetemplate<typenameT>Node<T>*Construct(T*post_order_arr,intsize,intk){Node<T>*Root=newNode<T>(post_order_arr[size-1]);if(size==1){returnRoot;}intheight_of_tree=ceil(log2(size*(k-1)+1)/log2(k))-1;intnodes_in_last_level=size-((pow(k,height_of_tree)-1)/(k-1));inttracker=0;while(tracker!=(size-1)){intlast_level_nodes=(pow(k,height_of_tree-1)>nodes_in_last_level)?nodes_in_last_level:(pow(k,height_of_tree-1));intnodes_in_next_subtree=((pow(k,height_of_tree-1)-1)/(k-1))+last_level_nodes;Root->set_next_child(Construct(post_order_arr+tracker,nodes_in_next_subtree,k));tracker=tracker+nodes_in_next_subtree;nodes_in_last_level=nodes_in_last_level-last_level_nodes;}returnRoot;}// Function to print the preorder traversaltemplate<typenameT>voidpreorder(Node<T>*Root){if(Root==NULL){return;}cout<<Root->get_data()<<" ";preorder(Root->get_first_child());preorder(Root->get_next_sibling());}// Driver codeintmain(){intM=9,N=3;intarr[]={5,6,7,2,8,9,3,4,1};// Function callpreorder(Construct(arr,M,N));return0;}
Java
// Java code to implement the approachimportjava.io.*;importjava.util.*;classGFG{// Function to calculate the// log base 2 of an integerpublicstaticintlog2(intN){// calculate log2 N indirectly// using log() methodintresult=(int)(Math.log(N)/Math.log(2));returnresult;}// Node ClasspublicstaticclassNode{intdata;// We use the first child/next sibling// representation to represent the TreeNodefirst_child;Nodenext_sibling;// Initializing Node using ConstructorpublicNode(intdata){this.first_child=null;this.next_sibling=null;this.data=data;}// Function to get the first childpublicNodeget_first_child(){returnthis.first_child;}// Function to get the siblingspublicNodeget_next_sibling(){returnthis.next_sibling;}// Function to set the next siblingpublicvoidset_next_sibling(Nodenode){if(this.next_sibling==null){this.next_sibling=node;}else{this.next_sibling.set_next_sibling(node);}}// Function to get the datapublicintget_data(){returnthis.data;}// Function to set the child node valuespublicvoidset_next_child(Nodenode){if(this.first_child==null){this.first_child=node;}else{this.first_child.set_next_sibling(node);}}}publicstaticvoidmain(String[]args){intM=9,N=3;int[]arr={5,6,7,2,8,9,3,4,1};// Function callpreorder(Construct(arr,0,M,N));}// Function to print the preorder traversalpublicstaticvoidpreorder(NodeRoot){if(Root==null){return;}System.out.println(Root.get_data()+" ");preorder(Root.get_first_child());preorder(Root.get_next_sibling());}// Function to construct the treepublicstaticNodeConstruct(int[]post_order_arr,inttracker,intsize,intk){NodeRoot=newNode(post_order_arr[tracker+size-1]);if(size==1){returnRoot;}intheight_of_tree=(int)Math.ceil(log2(size*(k-1)+1)/log2(k))-1;intnodes_in_last_level=size-(((int)Math.pow(k,height_of_tree)-1)/(k-1));intx=tracker;while(tracker!=(size-1)){intlast_level_nodes=((int)Math.pow(k,height_of_tree-1)>nodes_in_last_level)?nodes_in_last_level:((int)Math.pow(k,height_of_tree-1));intnodes_in_next_subtree=(((int)Math.pow(k,height_of_tree-1)-1)/(k-1))+last_level_nodes;Root.set_next_child(Construct(post_order_arr,tracker,nodes_in_next_subtree,k));tracker=tracker+nodes_in_next_subtree;nodes_in_last_level=nodes_in_last_level-last_level_nodes;}returnRoot;}}
Python3
# Python code to implement the approachimportmath# Node ClassclassNode:# We use the first child/next sibling representation to represent the Treedef__init__(self,data):self.data=dataself.first_child=Noneself.next_sibling=None# Function to get the first childdefget_first_child(self):returnself.first_child# Function to get the siblingsdefget_next_sibling(self):returnself.next_sibling# Function to set next siblingdefset_next_sibling(self,node):ifself.next_siblingisNone:self.next_sibling=nodeelse:self.next_sibling.set_next_sibling(node)# Function to set the child node valuedefset_next_child(self,node):ifself.first_childisNone:self.first_child=nodeelse:self.first_child.set_next_sibling(node)# Function to get the datadefget_data(self):returnself.data# Function to construct the treedefConstruct(post_order_arr,size,k):Root=Node(post_order_arr[size-1])ifsize==1:returnRootheight_of_tree=math.ceil(math.log(size*(k-1)+1,2)/math.log(k,2))-1nodes_in_last_level=size-((pow(k,height_of_tree)-1)/(k-1))tracker=0whiletracker!=(size-1):ifpow(k,height_of_tree-1)>nodes_in_last_level:last_level_nodes=int(nodes_in_last_level)else:last_level_nodes=int((pow(k,height_of_tree-1)))nodes_in_next_subtree=int(((pow(k,height_of_tree-1)-1)/(k-1))+last_level_nodes)Root.set_next_child(Construct(post_order_arr[tracker:],nodes_in_next_subtree,k))tracker=tracker+nodes_in_next_subtreenodes_in_last_level=nodes_in_last_level-last_level_nodesreturnRoot# Function to print the preorder traversaldefpreorder(root):ifroot==None:returnprint(root.get_data(),end=" ")preorder(root.get_first_child())preorder(root.get_next_sibling())# Driver codeif__name__=='__main__':M=9N=3arr=[5,6,7,2,8,9,3,4,1]# Function callpreorder(Construct(arr,M,N))# This code is contributed by Tapesh(tapeshdua420)
C#
// C# code to implement the approachusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Node ClassclassProgram{publicclassNode{intdata;// We use the first child/next sibling// representation to represent the TreeNodefirst_child;Nodenext_sibling;publicNode(intdata){this.first_child=null;this.next_sibling=null;this.data=data;}// Function to get the first childpublicNodeget_first_child(){returnthis.first_child;}// Function to get the siblingspublicNodeget_next_sibling(){returnthis.next_sibling;}// Function to set next siblingpublicvoidset_next_sibling(Nodenode){if(this.next_sibling==null){this.next_sibling=node;}else{this.next_sibling.set_next_sibling(node);}}// Function to get the datapublicintget_data(){returnthis.data;}// Function to set the child node valuepublicvoidset_next_child(Nodenode){if(this.first_child==null){this.first_child=node;}else{this.first_child.set_next_sibling(node);}}}// Driver codepublicstaticvoidMain(string[]args){intM=9,N=3;int[]arr={5,6,7,2,8,9,3,4,1};preorder(Construct(arr,M,N));}// Function to print the preorder traversalpublicstaticvoidpreorder(NodeRoot){if(Root==null){return;}Console.Write(Root.get_data()+" ");preorder(Root.get_first_child());preorder(Root.get_next_sibling());}// Function to construct the treepublicstaticNodeConstruct(int[]post_order_arr,intsize,intk){NodeRoot=newNode(post_order_arr[size-1]);if(size==1){returnRoot;}intheight_of_tree=(int)Math.Ceiling((double)(Math.Log(size*(k-1)+1,2)/Math.Log(k,2))-1);// Console.WriteLine(height_of_tree);intnodes_in_last_level=size-(((int)Math.Pow(k,height_of_tree)-1)/(k-1));inttracker=0;while(tracker!=(size-1)){intlast_level_nodes=((int)Math.Pow(k,height_of_tree-1)>nodes_in_last_level)?nodes_in_last_level:((int)Math.Pow(k,height_of_tree-1));intnodes_in_next_subtree=(int)((Math.Pow(k,height_of_tree-1)-1)/(k-1))+last_level_nodes;Root.set_next_child(Construct((post_order_arr.Skip(tracker)).Cast<int>().ToArray(),nodes_in_next_subtree,k));tracker=tracker+nodes_in_next_subtree;nodes_in_last_level=nodes_in_last_level-last_level_nodes;}returnRoot;}}// This Code is contributed by Tapesh(tapeshdua420)
JavaScript
// JavaScript code for the above approach// Node ClassclassNode{// We use the first child/next sibling representation to represent the Treeconstructor(data){this.data=data;this.firstChild=null;this.nextSibling=null;}// Function to get the first childgetFirstChild(){returnthis.firstChild;}// Function to get the siblingsgetNextSibling(){returnthis.nextSibling;}// Function to set next siblingsetNextSibling(node){if(this.nextSibling===null){this.nextSibling=node;}else{this.nextSibling.setNextSibling(node);}}// Function to set the child node valuesetNextChild(node){if(this.firstChild===null){this.firstChild=node;}else{this.firstChild.setNextSibling(node);}}// Function to get the datagetData(){returnthis.data;}}// Function to construct the treefunctionconstruct(postOrderArr,size,k){constroot=newNode(postOrderArr[size-1]);if(size===1){returnroot;}constheightOfTree=Math.ceil((Math.log((size*(k-1))+1,2)/Math.log(k,2)))-1;letnodesInLastLevel=size-((Math.pow(k,heightOfTree)-1)/(k-1));lettracker=0;while(tracker!==size-1){letlastLevelNodes;if(Math.pow(k,heightOfTree-1)>nodesInLastLevel){lastLevelNodes=Math.floor(nodesInLastLevel);}else{lastLevelNodes=Math.floor(Math.pow(k,heightOfTree-1));}constnodesInNextSubtree=Math.floor(((Math.pow(k,heightOfTree-1)-1)/(k-1))+lastLevelNodes);root.setNextChild(construct(postOrderArr.slice(tracker,tracker+nodesInNextSubtree),nodesInNextSubtree,k));tracker+=nodesInNextSubtree;nodesInLastLevel-=lastLevelNodes;}returnroot;}// Function to print the preorder traversalfunctionpreorder(root){if(root===null){return;}console.log(root.getData()+" ");preorder(root.getFirstChild());preorder(root.getNextSibling());}// Driver codeconstM=9;constN=3;constarr=[5,6,7,2,8,9,3,4,1];// Function callpreorder(construct(arr,M,N));// This code is contributed by Potta Lokesh
Output
1 2 5 6 7 3 8 9 4
Time Complexity: O(M) Auxiliary Space: O(M) for building the tree