A full k –ary tree is a tree where each node has either 0 or k children. Given an array which contains the preorder traversal of full k–ary tree, write a function that construct the full k –ary tree.

Difficulty level

This exercise is mostly suitable for students
typedef struct node1 {
char data;
struct node **children;
} *NaryTree;
NaryTree buildKtree_h(char A[], int size, int k, int *count)
{
NaryTree newnode;
int i;
if(size<=0) return NULL;
newnode=(NaryTree)malloc(sizeof(struct node));
if(!newnode) return NULL;
newnode->children=(NaryTree*)malloc(k * sizeof(NaryTree));
newnode->data=A[*count];
for(i=0;i<k;i++)
{
if (*count < size)
{
(*count)++;
newnode->children[i]=buildKtree_h(A,size,k,count);
}
else
newnode->children[i]=NULL;
}
return newnode;
}
NaryTree buildKtree(char A[], int k)
{
int count = 0;
return buildKtree_h(A, strlen(A), k, &count);
}
//Call NaryTree E= buildKtree("ABEFGCHIJD", 3);
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
