Construct the full k-ary tree from its preorder traversal
Last Updated : 30 Dec, 2025
Given an array that contains the preorder traversal of the full and complete k-ary tree, the task is to construct the full k-ary tree and return its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children and it is also complete means the nodes are filled from left to right at every level and every level is full except possibly the last level and nodes of the last level must be filled from left to right.
Examples:
Input: pre[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4}, k = 3 Output: Postorder traversal of constructed full k-ary tree is: 5 6 7 2 8 9 10 3 4 1 Explanation:
Approach:
The idea is to first compute height of the given tree and then build the tree using the height and an index variable that keeps track of the next node to be considered. Whey do we need height? If we do not know height, then we cannot decide whether the next node is a child or a sibling of the current node.
There are mainly two methods
Height Calculation
Computes the height of a full k-ary tree given number of nodes n and branching factor k.
Keeps adding nodes level by level (pow(k, h)) until total ≥ n.
Returns the minimum height h needed
Tree Construction
We maintain an index variable ind into preorder array. This variable is passed by reference so that it is shared among all
Base Case : If no nodes left or height exhausted, return nullptr.
Create a new node with pre[ind].
For each of the k children: If there’s a next value and height left, Increment ind and recursively build the subtree.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of a node of an n-ary treestructNode{intkey;vector<Node*>child;Node(intvalue,intk){key=value;child.clear();for(inti=0;i<k;i++)child.push_back(nullptr);}};// Build full k-ary tree from preorderNode*BuildKaryTree(constintpre[],intn,intk,inth,int&ind){if(ind>=n||h<=0)returnnullptr;Node*root=newNode(pre[ind],k);for(inti=0;i<k;i++){if(ind+1<n&&h>1){ind++;root->child[i]=BuildKaryTree(pre,n,k,h-1,ind);}}returnroot;}// Compute height for a full k-ary tree from nintComputeHeight(intn,intk){inth=0,total=0;while(total<n){total+=pow(k,h);h++;}returnh;}// Postorder traversalvoidpostord(Node*root,intk){if(!root)return;for(inti=0;i<k;i++)postord(root->child[i],k);cout<<root->key<<" ";}intmain(){intpre[]={1,2,5,6,7,3,8,9,10,4};intn=sizeof(pre)/sizeof(pre[0]);intk=3;intind=0;intheight=ComputeHeight(n,k);Node*root=BuildKaryTree(pre,n,k,height,ind);cout<<"Postorder traversal of constructed full k-ary tree is: ";postord(root,k);cout<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.List;// Structure of a node of an n-ary treeclassNode{intkey;List<Node>child=newArrayList<>();// Normal constructor (no initializer list)Node(intvalue,intk){key=value;for(inti=0;i<k;i++)child.add(null);}}publicclassMain{// Build full k-ary tree from preorderstaticNodeBuildKaryTree(int[]pre,intn,intk,inth,int[]ind){if(ind[0]>=n||h<=0)returnnull;Noderoot=newNode(pre[ind[0]],k);for(inti=0;i<k;i++){if(ind[0]+1<n&&h>1){ind[0]++;root.child.set(i,BuildKaryTree(pre,n,k,h-1,ind));}}returnroot;}// Compute height for a full k-ary tree from nstaticintComputeHeight(intn,intk){inth=0,total=0;while(total<n){total+=(int)Math.pow(k,h);h++;}returnh;}// Postorder traversalstaticvoidpostord(Noderoot,intk){if(root==null)return;for(inti=0;i<k;i++)postord(root.child.get(i),k);System.out.print(root.key+" ");}publicstaticvoidmain(String[]args){int[]pre={1,2,5,6,7,3,8,9,10,4};intn=pre.length;intk=3;int[]ind={0};intheight=ComputeHeight(n,k);Noderoot=BuildKaryTree(pre,n,k,height,ind);System.out.print("Postorder traversal of constructed full k-ary tree is: ");postord(root,k);System.out.println();}}
Python
importmath# Structure of a node of an n-ary treeclassNode:def__init__(self,value,k):self.key=valueself.child=[None]*k# Build full k-ary tree from preorderdefBuildKaryTree(pre,n,k,h,ind):ifind[0]>=norh<=0:returnNoneroot=Node(pre[ind[0]],k)foriinrange(k):ifind[0]+1<nandh>1:ind[0]+=1root.child[i]=BuildKaryTree(pre,n,k,h-1,ind)returnroot# Compute height for a full k-ary tree from ndefComputeHeight(n,k):h=0total=0whiletotal<n:total+=int(math.pow(k,h))h+=1returnh# Postorder traversaldefpostord(root,k):ifrootisNone:returnforiinrange(k):postord(root.child[i],k)print(root.key,end=' ')if__name__=='__main__':pre=[1,2,5,6,7,3,8,9,10,4]n=len(pre)k=3ind=[0]height=ComputeHeight(n,k)root=BuildKaryTree(pre,n,k,height,ind)print('Postorder traversal of constructed full k-ary tree is:',end=' ')postord(root,k)print()
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a node of an n-ary treepublicclassNode{publicintkey;publicList<Node>child=newList<Node>();// Normal constructor (no initializer list)publicNode(intvalue,intk){key=value;for(inti=0;i<k;i++)child.Add(null);}}publicclassProgram{// Build full k-ary tree from preorderstaticNodeBuildKaryTree(int[]pre,intn,intk,inth,refintind){if(ind>=n||h<=0)returnnull;Noderoot=newNode(pre[ind],k);for(inti=0;i<k;i++){if(ind+1<n&&h>1){ind++;root.child[i]=BuildKaryTree(pre,n,k,h-1,refind);}}returnroot;}// Compute height for a full k-ary tree from nstaticintComputeHeight(intn,intk){inth=0,total=0;while(total<n){total+=(int)Math.Pow(k,h);h++;}returnh;}// Postorder traversalstaticvoidpostord(Noderoot,intk){if(root==null)return;for(inti=0;i<k;i++)postord(root.child[i],k);Console.Write(root.key+" ");}staticvoidMain(string[]args){int[]pre={1,2,5,6,7,3,8,9,10,4};intn=pre.Length;intk=3;intind=0;intheight=ComputeHeight(n,k);Noderoot=BuildKaryTree(pre,n,k,height,refind);Console.Write("Postorder traversal of constructed full k-ary tree is: ");postord(root,k);Console.WriteLine();}}
JavaScript
classNode{constructor(value,k){this.key=value;this.child=Array(k).fill(null);}}functionBuildKaryTree(pre,n,k,h,ind){if(ind>=n||h<=0)returnnull;letroot=newNode(pre[ind],k);for(leti=0;i<k;i++){if(ind+1<n&&h>1){ind++;root.child[i]=BuildKaryTree(pre,n,k,h-1,ind);}}returnroot;}functionComputeHeight(n,k){leth=0,total=0;while(total<n){total+=Math.pow(k,h);h++;}returnh;}functionpostord(root,k){if(root===null)return;for(leti=0;i<k;i++)postord(root.child[i],k);process.stdout.write(root.key+'');}letpre=[1,2,5,6,7,3,8,9,10,4];letn=pre.length;letk=3;letind=0;letheight=ComputeHeight(n,k);letroot=BuildKaryTree(pre,n,k,height,ind);process.stdout.write('Postorder traversal of constructed full k-ary tree is: ');postord(root,k);console.log();
Output
Postorder traversal of constructed full k-ary tree is: 5 6 7 2 8 9 10 3 4 1