A n-ary tree is a tree in which each node has at most $\texttt{n}$ children. The binary tree is a special case of n-ary tree in which n = 2. 

Given the following n-ary tree structure

#define n ...
typedef ... element;
typedef struct node {
     
element data;
     
struct node *children[n];
} * NaryTree;

  1. Write a recursive function that performs the postorder traversal of the n-ary tree.
  2. Write a recursive function that returns the number of leaves in a n-ary tree. Without performing any calculations, give the worst case time complexity of your function. Justify your answer.
  3. Write an iterative function that returns the maximum width of an n-ary tree. We define the maximum width of an n-ary tree as the maximum number of nodes located at the same level. Without performing any calculations, give the worst case time complexity of your function. Justify your answer.

Difficulty level
This exercise is mostly suitable for students
void postorder(naryTree B)
{
	int i;
	if (B)
	{
		for (i = 0; i < n; i++)
			postorder(B->children[i]);
		printf(" %d ", B->data );
	}
}


int nb_leaves(naryTree B)
{
	int  i, count = 0  , leaf = 1;
	if (!B) return 0;
	for (i = 0; i < n; i++)
		if (leaf == 1 && B->children[i] != NULL)
			leaf = 0;
	if (leaf == 1)
		return 1
		;
	for (i = 0; i < n; i++)
		count += nb_leaves(B->children[i]);
	return count;
}




int width(naryTree A)
{
	int lcour = 0, lmax = 0, nivcour = 1,i;
	queue f;
	element1 E, X;

	if (A == NULL) return 0;
	f = CreateQueue();

	E.tree = A;
	E.level = 1;
	EnQueue(&f, E);
	while (Front(f, &E))
	{
		if (E.level == nivcour) lcour++;
		else
		{
			if (lcour > lmax) lmax = lcour;
			lcour = 1;
			nivcour = E.level;
		}
		DeQueue(&f);
		for(i=0;i<n;i++)
			if (E.tree->children[i]) 
			{ 
				X.tree = E.tree->children[i]; 
				X.level = E.level + 1; 
				EnQueue(&f, X); 
			}
	}
	return lmax;
}


Back to the list of exercises
Looking for a more challenging exercise, try this one !!
UVA 1112 - Mice and Maze