Consider the following declaration of a BST in which the field nbd denotes the number of descendants of a tree node:

typedef struct node
{
    
element data ;
    
int nbd ;
    
struct node *Left, *Right ;
} *BST;

 

  • Write a function that inserts an element to a BST;
  • Write a function that tests that the field nbd of each BST node is correct.

Difficulty level
This exercise is mostly suitable for students
int insert_BST(BST *B, element1 e)
{
	int v;
	if(*B==NULL)
	{
		*B=(BST)malloc(sizeof(struct node));
		(*B)->data=e;
		(*B)->right=(*B)->left=NULL;
		(*B)->nbd=0;
		return 1;
	}
	if((*B)->data==e)
		return 0;
	if((*B)->data < e)
		return insert_BST(&((*B)->right),e) && ++((*B)->nbd); 
	else
		return insert_BST(&((*B)->left),e) && ++((*B)->nbd); 
}

int check(BST B)
{
	int i=0;
	return check_r(B,&i);
}

int check_r(BST B, int *e)
{
	int l=1,r=1,e1=0,e2=0;
	if(B==NULL) return 1;
	if(B->left==NULL && B->right==NULL)
	{
		*e=B->nbd;
		return (B->nbd==0);
	}
	if(B->left)
	{
		l=check_r(B->left,&e1);
		e1++;
	}
	if(B->right)
	{
		r=check_r(B->right,&e2);
		e2++;
	}

	if((e1+e2)==B->nbd)
	{
		*e=e1+e2;
		return l && r;
	}
	return 0;
		
}

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