The following function checks whether a given binary tree dynamically implemented is a BST or not.
int isBST(Btree tree)
{
if(tree == NULL) return 1;
if(tree->left != NULL && FindMax(tree->left) > tree->data) return 0;
if(tree->right != NULL && FindMin(tree->right) < tree->data) return 0;
if(!isBST(tree->left) || !isBST(tree->right)) return 0;
return 1;
}
$\texttt{FindMax}$ and $\texttt{FindMin}$ are 2 auxiliary functions that returns the maximum (resp. minimum) element of a $\texttt{BST}$.
element FindMin(Btree tree)
{
if (tree==NULL) return INT_MAX;
return min(tree->data,min(FindMin(tree->left),FindMin(tree->right)));
}
element FindMax(Btree tree)
{
if (tree==NULL) return INT_MIN;
return max(tree->data,max(FindMax(tree->left),FindMax(tree->right)));
}
- Without performing calculation, give the worst-case time complexity of the $\texttt{isBST}$ function. Justify your answer.
- Note that the inorder traversal of BSTs produces sorted lists. While traversing the BST in inorder, and at each node, check the condition that its key value should be greater then the key value of its previous visited node.
Write a recursive function that checks whether a given binary tree is a BST or not given the above approach. - Without performing calculation, give the worst-case time complexity of your function written in the previosu part. Justify your answer.
Difficulty level
This exercise is mostly suitable for students
1. O(N^2)
2.
int isBST(Btree B, int *prev)
{
if(!B) return 1;
if(!isBST(B->left, prev)) return 0;
if(B->data< * prev) return 0;
*prev=B->data;
return isBST(B->right,prev);
}
from Main
int previous=INT_MIN;
printf("\n\n\nIsBST: %d \n\n\n", isBST(B,&previous));
3. O(N)
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using merge-sort algorithm