We consider a variant of BST where $\texttt{left(n)}$ $\leq$ $n$ $<$ $\texttt{right(n)}$ and this for any node $\texttt{n}$ in the tree.
Write a function that calculates the number of distinct values in this kind of binary tree. Give the corresponding declaration.
Difficulty level
This exercise is mostly suitable for students
int nb_distinct(BST B)
{
if(B)
{
if(B->left && B->data==B->left->data)
return nb_distinct(B->left) + nb_distinct(B->right);
return 1+ nb_distinct(B->left) + nb_distinct(B->right);
}
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Reverse a number using recursion