Write a function that computes the maximum width of a dynamically implemented BT. We define the maximum width of a BT as the maximum number of nodes located at the same level.


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

int width(Btree A)
{
	int current_count = 0, max_count = 0, 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);}
    	}
    	if (current_count > max_count) 
                max_count = current_count;	
    	return max_count;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Length of the longest ascending sequence of characters