We define the maximum width of a BT as the maximum number of nodes located at the same level, and the maximum depth as the longest path from the root to a leaf. 

  • Write a function that computes the maximum width of a dynamically implemented BT.
  • Write a function that computes the maximum depth of a statically implemented BT.

Difficulty level
This exercise is mostly suitable for students
typedef  struct 
{
	Btree tree; 
	int level;
} element;



int width(Btree A)
{
    	int current_count = 1, max_count = 1, current_level = 1;
	queue q;
	element E, X;

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

    	E.tree = A;
    	E.level = 1;
	EnQueue(&q,E);
	while(Front(q,&E))
    	{
        	if (E.level == current_level) current_count++ ;
        	else
        	{
            		if (current_count > max_count) 
                		max_count = current_count;
            		current_count = 1;
            		current_level = E.level;
        	}
		DeQueue(&q);
        	if (E.tree->left) {X.tree = E.tree->left; X.level = E.level+1; EnQueue(&q,X);}
        	if (E.tree->right) {X.tree = E.tree->right; X.level = E.level+1; EnQueue(&q,X);}
    	}
    	return max_count;
}






int depth(AB A)
{
	return depth_rec(A,A.ind_root);
}
int depth_rec(AB A, int i)
{
	if (i == 0 || A.Tab[i].iLEFT == -1) return 0;
	return 1 + max(depth_rec(A,A.Tab[i].iLEFT),depth_rec(A,A.Tab[i].iRIGHT));
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using merge-sort algorithm