Construct a Complete N-ary Tree from given Postorder Traversal
Last Updated :
23 Jul, 2025
Given an array arr[] 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.
Examples:
Input: arr[] = {5, 6, 7, 2, 8, 9, 3, 4, 1}, N = 3
Output:
The tree structure for above example
Input: arr[] = {7, 8, 9, 2, 3, 4, 5, 6, 1}, N = 5
Output:
Complete structure for the 2nd example
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.
So height (H) = ceil[ log3(9*2 + 1) ] - 1 = ceil[log319] - 1 = 3 - 1 = 2 and L = 9 - (32 - 1)/2 = 5.
1st step: So the root = 1
1st step of forming the tree
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>
using namespace std;
// Node Class
template <typename T> class Node {
public:
Node(T data);
// Get the first child of the Node
Node* get_first_child() const;
// Get the Next Sibling of The node
Node* get_next_sibling() const;
// Sets the next sibling of the node
void set_next_sibling(Node* node);
// Sets the next child of the node
void set_next_child(Node* node);
// Returns the data the node contains
T get_data();
private:
T data;
// We use the first child/next sibling representation
// to represent the Tree
Node* first_child;
Node* next_sibling;
};
// Using template for generic usage
template <typename T> Node<T>::Node(T data)
{
first_child = NULL;
next_sibling = NULL;
this->data = data;
}
// Function to get the first child
template <typename T>
Node<T>* Node<T>::get_first_child() const
{
return first_child;
}
// Function to get the siblings
template <typename T>
Node<T>* Node<T>::get_next_sibling() const
{
return next_sibling;
}
// Function to set next sibling
template <typename T>
void Node<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 data
template <typename T> T Node<T>::get_data() { return data; }
// Function to set the child node value
template <typename T>
void Node<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 tree
template <typename T>
Node<T>* Construct(T* post_order_arr, int size, int k)
{
Node<T>* Root = new Node<T>(post_order_arr[size - 1]);
if (size == 1) {
return Root;
}
int height_of_tree
= ceil(log2(size * (k - 1) + 1) / log2(k)) - 1;
int nodes_in_last_level
= size - ((pow(k, height_of_tree) - 1) / (k - 1));
int tracker = 0;
while (tracker != (size - 1)) {
int last_level_nodes
= (pow(k, height_of_tree - 1)
> nodes_in_last_level)
? nodes_in_last_level
: (pow(k, height_of_tree - 1));
int nodes_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;
}
return Root;
}
// Function to print the preorder traversal
template <typename T> void preorder(Node<T>* Root)
{
if (Root == NULL) {
return;
}
cout << Root->get_data() << " ";
preorder(Root->get_first_child());
preorder(Root->get_next_sibling());
}
// Driver code
int main()
{
int M = 9, N = 3;
int arr[] = { 5, 6, 7, 2, 8, 9, 3, 4, 1 };
// Function call
preorder(Construct(arr, M, N));
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to calculate the
// log base 2 of an integer
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
// Node Class
public static class Node {
int data;
// We use the first child/next sibling
// representation to represent the Tree
Node first_child;
Node next_sibling;
// Initializing Node using Constructor
public Node(int data)
{
this.first_child = null;
this.next_sibling = null;
this.data = data;
}
// Function to get the first child
public Node get_first_child()
{
return this.first_child;
}
// Function to get the siblings
public Node get_next_sibling()
{
return this.next_sibling;
}
// Function to set the next sibling
public void set_next_sibling(Node node)
{
if (this.next_sibling == null) {
this.next_sibling = node;
}
else {
this.next_sibling.set_next_sibling(node);
}
}
// Function to get the data
public int get_data() { return this.data; }
// Function to set the child node values
public void set_next_child(Node node)
{
if (this.first_child == null) {
this.first_child = node;
}
else {
this.first_child.set_next_sibling(node);
}
}
}
public static void main(String[] args)
{
int M = 9, N = 3;
int[] arr = { 5, 6, 7, 2, 8, 9, 3, 4, 1 };
// Function call
preorder(Construct(arr, 0, M, N));
}
// Function to print the preorder traversal
public static void preorder(Node Root)
{
if (Root == null) {
return;
}
System.out.println(Root.get_data() + " ");
preorder(Root.get_first_child());
preorder(Root.get_next_sibling());
}
// Function to construct the tree
public static Node Construct(int[] post_order_arr,
int tracker, int size,
int k)
{
Node Root = new Node(post_order_arr[tracker+size - 1]);
if (size == 1) {
return Root;
}
int height_of_tree
= (int)Math.ceil(log2(size * (k - 1) + 1)
/ log2(k))
- 1;
int nodes_in_last_level
= size
- (((int)Math.pow(k, height_of_tree) - 1)
/ (k - 1));
int x=tracker;
while (tracker != (size - 1)) {
int last_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));
int nodes_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;
}
return Root;
}
}
Python3
# Python code to implement the approach
import math
# Node Class
class Node:
# We use the first child/next sibling representation to represent the Tree
def __init__(self, data):
self.data = data
self.first_child = None
self.next_sibling = None
# Function to get the first child
def get_first_child(self):
return self.first_child
# Function to get the siblings
def get_next_sibling(self):
return self.next_sibling
# Function to set next sibling
def set_next_sibling(self, node):
if self.next_sibling is None:
self.next_sibling = node
else:
self.next_sibling.set_next_sibling(node)
# Function to set the child node value
def set_next_child(self, node):
if self.first_child is None:
self.first_child = node
else:
self.first_child.set_next_sibling(node)
# Function to get the data
def get_data(self):
return self.data
# Function to construct the tree
def Construct(post_order_arr, size, k):
Root = Node(post_order_arr[size - 1])
if size == 1:
return Root
height_of_tree = math.ceil(
math.log(size * (k - 1) + 1, 2) / math.log(k, 2)) - 1
nodes_in_last_level = size - ((pow(k, height_of_tree) - 1) / (k - 1))
tracker = 0
while tracker != (size - 1):
if pow(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_subtree
nodes_in_last_level = nodes_in_last_level - last_level_nodes
return Root
# Function to print the preorder traversal
def preorder(root):
if root == None:
return
print(root.get_data(), end=" ")
preorder(root.get_first_child())
preorder(root.get_next_sibling())
# Driver code
if __name__ == '__main__':
M = 9
N = 3
arr = [5, 6, 7, 2, 8, 9, 3, 4, 1]
# Function call
preorder(Construct(arr, M, N))
# This code is contributed by Tapesh(tapeshdua420)
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
using System.Linq;
// Node Class
class Program {
public class Node {
int data;
// We use the first child/next sibling
// representation to represent the Tree
Node first_child;
Node next_sibling;
public Node(int data)
{
this.first_child = null;
this.next_sibling = null;
this.data = data;
}
// Function to get the first child
public Node get_first_child()
{
return this.first_child;
}
// Function to get the siblings
public Node get_next_sibling()
{
return this.next_sibling;
}
// Function to set next sibling
public void set_next_sibling(Node node)
{
if (this.next_sibling == null) {
this.next_sibling = node;
}
else {
this.next_sibling.set_next_sibling(node);
}
}
// Function to get the data
public int get_data() { return this.data; }
// Function to set the child node value
public void set_next_child(Node node)
{
if (this.first_child == null) {
this.first_child = node;
}
else {
this.first_child.set_next_sibling(node);
}
}
}
// Driver code
public static void Main(string[] args)
{
int M = 9, N = 3;
int[] arr = { 5, 6, 7, 2, 8, 9, 3, 4, 1 };
preorder(Construct(arr, M, N));
}
// Function to print the preorder traversal
public static void preorder(Node Root)
{
if (Root == null) {
return;
}
Console.Write(Root.get_data() + " ");
preorder(Root.get_first_child());
preorder(Root.get_next_sibling());
}
// Function to construct the tree
public static Node Construct(int[] post_order_arr,
int size, int k)
{
Node Root = new Node(post_order_arr[size - 1]);
if (size == 1) {
return Root;
}
int height_of_tree = (int)Math.Ceiling(
(double)(Math.Log(size * (k - 1) + 1, 2)
/ Math.Log(k, 2))
- 1);
// Console.WriteLine(height_of_tree);
int nodes_in_last_level
= size
- (((int)Math.Pow(k, height_of_tree) - 1)
/ (k - 1));
int tracker = 0;
while (tracker != (size - 1)) {
int last_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));
int nodes_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;
}
return Root;
}
}
// This Code is contributed by Tapesh(tapeshdua420)
JavaScript
// JavaScript code for the above approach
// Node Class
class Node {
// We use the first child/next sibling representation to represent the Tree
constructor(data) {
this.data = data;
this.firstChild = null;
this.nextSibling = null;
}
// Function to get the first child
getFirstChild() {
return this.firstChild;
}
// Function to get the siblings
getNextSibling() {
return this.nextSibling;
}
// Function to set next sibling
setNextSibling(node) {
if (this.nextSibling === null) {
this.nextSibling = node;
} else {
this.nextSibling.setNextSibling(node);
}
}
// Function to set the child node value
setNextChild(node) {
if (this.firstChild === null) {
this.firstChild = node;
} else {
this.firstChild.setNextSibling(node);
}
}
// Function to get the data
getData() {
return this.data;
}
}
// Function to construct the tree
function construct(postOrderArr, size, k) {
const root = new Node(postOrderArr[size - 1]);
if (size === 1) {
return root;
}
const heightOfTree = Math.ceil((Math.log((size * (k - 1)) + 1, 2) / Math.log(k, 2))) - 1;
let nodesInLastLevel = size - ((Math.pow(k, heightOfTree) - 1) / (k - 1));
let tracker = 0;
while (tracker !== size - 1) {
let lastLevelNodes;
if (Math.pow(k, heightOfTree - 1) > nodesInLastLevel) {
lastLevelNodes = Math.floor(nodesInLastLevel);
} else {
lastLevelNodes = Math.floor(Math.pow(k, heightOfTree - 1));
}
const nodesInNextSubtree = 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;
}
return root;
}
// Function to print the preorder traversal
function preorder(root) {
if (root === null) {
return;
}
console.log(root.getData() + " ");
preorder(root.getFirstChild());
preorder(root.getNextSibling());
}
// Driver code
const M = 9;
const N = 3;
const arr = [5, 6, 7, 2, 8, 9, 3, 4, 1];
// Function call
preorder(construct(arr, M, N));
// This code is contributed by Potta Lokesh
Time Complexity: O(M)
Auxiliary Space: O(M) for building the tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem