Construct a Complete N-ary Tree from given Postorder Traversal
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) + NHThe 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.
3nd 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 aproach #include <bits/stdc++.h>using namespace std; // Node Classtemplate <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 usagetemplate <typename T> Node<T>::Node(T data){ first_child = NULL; next_sibling = NULL; this->data = data;} // Function to get the first childtemplate <typename T>Node<T>* Node<T>::get_first_child() const{ return first_child;} // Function to get the siblingstemplate <typename T>Node<T>* Node<T>::get_next_sibling() const{ return next_sibling;} // Function to set next siblingtemplate <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 datatemplate <typename T> T Node<T>::get_data() { return data; } // Function to set the child node valuetemplate <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 treetemplate <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 traversaltemplate <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 codeint 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;} |
1 2 5 6 7 3 8 9 4
Time Complexity: O(M)
Auxiliary Space: O(M) for building the tree









.png)