Earth Hour

Sunday, April 17, 2011

Finding whether a Binary tree is BST or not

Hi folks!
It has been quite sometime since I posted on this blog. Anyways, yesterday a friend asked me this question, given a binary tree (not necessarily Binary Search Tree) find whether it is BST(Binary Search Tree) or not.
Well, the question is pretty straight forward. A small thought on the basic definition of BST will lead us to answer this. As we know, BST holds the property that for every node of the tree its left child (if exists) contains value strictly less than the current node and its right child (if exists) contains value strictly greater than the current code.
Now, if we implement the above logic we may end up marking the below tree as bst which is wrong:-

8
4 10
2 12

A little thought on this reveals the problem with above logic is we are not checking the range for every node. So here goes my C++ implementation (but pretty straight forward. Pardon the syntax errors) with range checking:-
Let the structure of every node is:

struct bst{
int val;
bst *left;
bst *right;
}

So now our function goes:

bool isbst(const bst *T,const int &start, const int &end){
if(!T)
return true; //trivially true for empty tree

if(start <= T->val && T->val <= end){ //check current node lies within range [start,end]
bool left = isbst(T->left, start,T->val-1); //check left subtree is bst
bool right = isbst(T->right, T->val+1,end); //check right subtree is bst
if(left && right)
return true;
}else
return false; //value out of range;

return false; //never reached
}


This function is called like : isbst(root_node, INT_MIN, INT_MAX);
INT_MIN here signifies -infinity and INT_MAX as +infinity
Feedback welcome :)