Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children.
Examples:
Input : preorder[] = {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
Tree formed is: 1
/ | \
2 3 4
/|\ /|\
5 6 7 8 9 10
Input : preorder[] = {1, 2, 5, 6, 7, 3, 4}
k = 3
Output : Postorder traversal of constructed
full k-ary tree is: 5 6 7 2 4 3 1
Tree formed is: 1
/ | \
2 3 4
/|\
5 6 7
We have discussed this problem for Binary tree in below post.
Construct a special tree from given preorder traversal
In this post, solution for a k-ary tree is discussed.
In Preorder traversal, first root node is processed then followed by the left subtree and right subtree. Because of this, to construct a full k-ary tree, we just need to keep on creating the nodes without bothering about the previous constructed nodes. We can use this to build the tree recursively.
Following are the steps to solve the problem:
- Find the height of the tree.
- Traverse the preorder array and recursively add each node
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
vector<Node*> child;
};
Node* newNode( int value)
{
Node* nNode = new Node;
nNode->key = value;
return nNode;
}
Node* BuildKaryTree( int A[], int n, int k, int h, int & ind)
{
if (n <= 0)
return NULL;
Node* nNode = newNode(A[ind]);
if (nNode == NULL) {
cout << "Memory error" << endl;
return NULL;
}
for ( int i = 0; i < k; i++) {
if (ind < n - 1 && h > 1) {
ind++;
nNode->child.push_back(BuildKaryTree(A, n, k, h - 1, ind));
} else {
nNode->child.push_back(NULL);
}
}
return nNode;
}
Node* BuildKaryTree( int * A, int n, int k, int ind)
{
int height = ( int ) ceil ( log (( double )n * (k - 1) + 1)
/ log (( double )k));
return BuildKaryTree(A, n, k, height, ind);
}
void postord(Node* root, int k)
{
if (root == NULL)
return ;
for ( int i = 0; i < k; i++)
postord(root->child[i], k);
cout << root->key << " " ;
}
int main()
{
int ind = 0;
int k = 3, n = 10;
int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 };
Node* root = BuildKaryTree(preorder, n, k, ind);
cout << "Postorder traversal of constructed"
" full k-ary tree is: " ;
postord(root, k);
cout << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static class Node
{
int key;
Vector<Node> child;
};
static Node newNode( int value)
{
Node nNode = new Node();
nNode.key = value;
nNode.child= new Vector<Node>();
return nNode;
}
static int ind;
static Node BuildKaryTree( int A[], int n,
int k, int h)
{
if (n <= 0 )
return null ;
Node nNode = newNode(A[ind]);
if (nNode == null )
{
System.out.println( "Memory error" );
return null ;
}
for ( int i = 0 ; i < k; i++)
{
if (ind < n - 1 && h > 1 )
{
ind++;
nNode.child.add(BuildKaryTree(A, n, k, h - 1 ));
}
else
{
nNode.child.add( null );
}
}
return nNode;
}
static Node BuildKaryTree_1( int [] A, int n, int k, int in)
{
int height = ( int )Math.ceil(Math.log(( double )n * (k - 1 ) + 1 ) /
Math.log(( double )k));
ind = in;
return BuildKaryTree(A, n, k, height);
}
static void postord(Node root, int k)
{
if (root == null )
return ;
for ( int i = 0 ; i < k; i++)
postord(root.child.get(i), k);
System.out.print(root.key + " " );
}
public static void main(String args[])
{
int ind = 0 ;
int k = 3 , n = 10 ;
int preorder[] = { 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 };
Node root = BuildKaryTree_1(preorder, n, k, ind);
System.out.println( "Postorder traversal of " +
"constructed full k-ary tree is: " );
postord(root, k);
System.out.println();
}
}
|
Python3
from math import ceil, log
class newNode:
def __init__( self , value):
self .key = value
self .child = []
def BuildkaryTree(A, n, k, h, ind):
if (n < = 0 ):
return None
nNode = newNode(A[ind[ 0 ]])
if (nNode = = None ):
print ( "Memory error" )
return None
for i in range (k):
if (ind[ 0 ] < n - 1 and h > 1 ):
ind[ 0 ] + = 1
nNode.child.append(BuildkaryTree(A, n, k,
h - 1 , ind))
else :
nNode.child.append( None )
return nNode
def BuildKaryTree(A, n, k, ind):
height = int (ceil(log( float (n) * (k - 1 ) + 1 ) /
log( float (k))))
return BuildkaryTree(A, n, k, height, ind)
def postord(root, k):
if (root = = None ):
return
for i in range (k):
postord(root.child[i], k)
print (root.key, end = " " )
if __name__ = = '__main__' :
ind = [ 0 ]
k = 3
n = 10
preorder = [ 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 ]
root = BuildKaryTree(preorder, n, k, ind)
print ( "Postorder traversal of constructed" ,
"full k-ary tree is: " )
postord(root, k)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int key;
public List<Node> child;
};
static Node newNode( int value)
{
Node nNode = new Node();
nNode.key = value;
nNode.child= new List<Node>();
return nNode;
}
static int ind;
static Node BuildKaryTree( int []A, int n,
int k, int h)
{
if (n <= 0)
return null ;
Node nNode = newNode(A[ind]);
if (nNode == null )
{
Console.WriteLine( "Memory error" );
return null ;
}
for ( int i = 0; i < k; i++)
{
if (ind < n - 1 && h > 1)
{
ind++;
nNode.child.Add(BuildKaryTree(A, n, k, h - 1));
}
else
{
nNode.child.Add( null );
}
}
return nNode;
}
static Node BuildKaryTree_1( int [] A, int n, int k, int iN)
{
int height = ( int )Math.Ceiling(Math.Log(( double )n * (k - 1) + 1) /
Math.Log(( double )k));
ind = iN;
return BuildKaryTree(A, n, k, height);
}
static void postord(Node root, int k)
{
if (root == null )
return ;
for ( int i = 0; i < k; i++)
postord(root.child[i], k);
Console.Write(root.key + " " );
}
public static void Main(String []args)
{
int ind = 0;
int k = 3, n = 10;
int []preorder = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 };
Node root = BuildKaryTree_1(preorder, n, k, ind);
Console.WriteLine( "Postorder traversal of " +
"constructed full k-ary tree is: " );
postord(root, k);
Console.WriteLine();
}
}
|
Javascript
<script>
class Node
{
constructor(key) {
this .child = [];
this .key = key;
}
}
function newNode(value)
{
let nNode = new Node(value);
return nNode;
}
let ind;
function BuildKaryTree(A, n, k, h)
{
if (n <= 0)
return null ;
let nNode = newNode(A[ind]);
if (nNode == null )
{
document.write( "Memory error" );
return null ;
}
for (let i = 0; i < k; i++)
{
if (ind < n - 1 && h > 1)
{
ind++;
nNode.child.push(BuildKaryTree(A, n, k, h - 1));
}
else
{
nNode.child.push( null );
}
}
return nNode;
}
function BuildKaryTree_1(A, n, k, In)
{
let height = Math.ceil(Math.log(n * (k - 1) + 1) / Math.log(k));
ind = In;
return BuildKaryTree(A, n, k, height);
}
function postord(root, k)
{
if (root == null )
return ;
for (let i = 0; i < k; i++)
postord(root.child[i], k);
document.write(root.key + " " );
}
ind = 0;
let k = 3, n = 10;
let preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 ];
let root = BuildKaryTree_1(preorder, n, k, ind);
document.write( "Postorder traversal of " +
"constructed full k-ary" + "</br>" + "tree is: " );
postord(root, k);
document.write( "</br>" );
</script>
|
Output
Postorder traversal of constructed full k-ary tree is: 5 6 7 2 8 9 10 3 4 1
Time Complexity: O(n),the time complexity of this algorithm is O(n) where n is the number of elements in the given array. We traverse the given array once and create a k-ary tree from it, which takes linear time.
Auxiliary Space: O(n),the space complexity of this algorithm is also O(n) as we need to create a k-ary tree with the given elements in the array. We also need to store intermediate nodes in the function stack frame.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Dec, 2022
Like Article
Save Article