Here is the code for finding if the given binary tree was a binary search tree(BST) or not:
bool isBST(struct node* root)
{
// traverse the tree in inorder fashion and keep track of prev node
if (root)
{
struct node *prev = NULL;
if (!isBST(root->left))
return false;
// Allows only distinct valued nodes
if (prev != NULL && root->data <= prev->data)
return false;
prev = root;
return isBST(root->right);
}
return true;
}
However this does not give the correct output. when I changed my code to the below version it worked fine:
bool isbst(node * root)
{
static struct node * prev = NULL;
if( root)
{
if(!isbst(root->left))
return false;
if(prev != NULL && root->data < prev->data)
return false;
prev = root;
return isbst(root-> right);
}
return true;
}
My question is why does it work when the line static struct node * prev = NULL;
was added to the code?
In my previous code even though the variable 'prev' was declared again and again it was update to the root each time..my code should have worked fine. But it didn't. what is wrong with it?