Adobe Interview Question
Seems to be a correct answer, as all the below algo will fails when the right child of node X(which is a left child of its parent) is greater than X , but also greater than parent of x then the BST property of the tree gets voilated but the below stated also will pass.
Thus inorder is the best algo to find the BST .
The codes above would crash if node->left is NULL when you access node->left->value.
also it doesn't consider the case where the BST is not complete.
A more complete version is
bool isBST(bnode * root)
{
if(root == NULL)
return true;
else if((root->left == NULL)||(root->left == NULL))
{
if((root->left == NULL)&&(root->left == NULL))
return true;
else if((root->left==NULL)&&(root->id >= root->right->id))
return false;
else if ((root->right==NULL)&&(root->id < root->left->id))
return false;
}
else if((root->id < root->left->id) ||(root->id >= root->right->id))
return false;
else
return (isBST(root->left) && isBST(root->right));
}
Above algos are not correct, by just checking left and right child we can not be sure that it is a BST, we have to ensure that all the elements on right are bigger then the current node and all the elements on the left are smaller then the current one.
We can do this by passing minimum and maximum values while using recursion, search on google you will find the solution.
a better solution:
bool isthisBST(nodeptr root)
{
return isthisBSTUtil(root,INT_MIN, INT_MAX);
}
int isthisBSTUtil(nodeptr root, int min, int max)
{
if(root == NULL) return true; //empty tree is a bst
if(root-data < min || root->data >max) return false;
return (isthisBSTUtil(root->left, min, root->data) || isthis BSTUtil(root->right,root->data, max);
}
NOte: we call isthisBST(root,INT_MIN,INT_MAX);
the checkbst returns 1 if tree is BST and return zero otherwise
- vaibhav August 23, 2010int checkbst(struct node*node,int min,int max)//initial call is with min=INT_MIN and // max=INT_MAX
{
if (node==NULL) return 1;
if(node->data < min ||node->data>max) return 0;
return(checkbst(node->left,min,node->data && checkbst(node->right,node->data,max);
}