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.
👁 Example 2 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.
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.