Write a function that finds the level that has the maximum sum in the binary tree.


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




int maxsum(Btree A)
{
    	int current_sum = 0, 
    	    max_sum = INT_MIN, 
    	    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_sum +=E.tree->data;
        	else
        	{
            		if (current_sum > max_sum) 
                		max_sum = current_sum;
            		current_sum = E.tree->data;
            		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_sum;
}

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