A min-heap is a complete binary tree where the value of each element is less than the values of its children, if any. 

Remark: each value is unique in a heap (it can't be repeated).

  • Define the data structure for dynamic implementation of a heap of integers.
  • Write a function $$\texttt{belong}$$ that tests whether or not an element belongs to a heap.
  • Write a function $$\texttt{max}$$ that returns the maximum integer in a heap. Calculate the order of complexity of this algorithm in the best and in the worst cases. Justify your answer.
  • A heap A is said to be "domain included" in a heap B if the minimum element of A is greater than or equal to the minimum element of B and if the maximum element of A is less than or equal to the maximum element of B. Write a function to test if a heap A is $$\texttt{domain included}$$ in a heap B.

Difficulty level
Video recording
This exercise is mostly suitable for students
typedef int element;
typedef struct node{
	element data;
	struct node *left,*right;
} *heap ;

int belong(heap T, element e) 
{
	if (T == NULL) return 0 ;
	if (e < T->data) return 0 ;
	if (e == T->data) return 1 ;
	return (belong(T->left,e) || belong(T->right,e));
}

int max(heap T, element *e) 
{
	int maxleft, maxright;
	if (T == NULL)
		return 0 ;
	if ( T->left==NULL && T->right==NULL)
	{
		*e = T->data;
		return 1 ;
	}
	if ( T->right==NULL)
	{
		max(T->left, &maxleft) ;
		*e = maxleft;
		return 1 ;
	}
	max(T->right, &maxright) ;
	max(T->right, &maxleft) ;
	*e = (maxleft > maxright)? maxleft : maxright ; 
	return 1;
}


int domain(heap A, heap B) 
{
	int maxA, maxB;
	if (A == NULL) return 1 ;
	if (B == NULL) return 0 ;
	max(A,&maxA);
	max(B,&maxB);
	return (A->data >= B->data && maxA <= maxB);
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Reverse a number using recursion