Write each time a function that returns the maximum value of all the nodes in a binary tree of integers. Assume all values are nonnegative; return -1 if the tree is empty.

  • recursive function
  • iterartive using a queue
  • iterative using a stack

Difficulty level
This exercise is mostly suitable for students
int max_rec(Btree B)
{
	if(B==NULL)
		return -1;
	return max(max(max_rec(B->left),max_rec(B->right)),B->data);
}



int max_iter_stack(Btree B)
{
	stack s=CreateStack();
	int proceed = 1;
	int max = -1;

	while(proceed)
	{
		while(B != NULL)
		{
			Push(&s,B);
			B=B->left;
		}
		if(!isEmptyStack(s))
		{
			Top(s,&B);
			Pop(&s);
			if(B->data>max)
			    max= B->data;
			B=B->right;
		}
		else
			proceed=0;
	}
	return max;
}

int max_iter_queue(Btree B)
{
	queue q = CreateQueue();
	Btree temp;
	int max = -1;

	if(B==NULL) return max;

	EnQueue(&q,B);

	while(Front(q,&temp))
	{
		DeQueue(&q);
		if(temp->data>max)
			    max= temp->data;
		if(temp->left != NULL)
			EnQueue(&q,temp->left);
		if(temp->right != NULL)
			EnQueue(&q,temp->right);
	}
	return max;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Program output 7