Thursday, October 1, 2009

Check Whether a tree is a binary Search Tree or not

Iterate over the Binary Search Tree. Keep track of the last node traversed. If you find at any point the prev node > the current node under examination return false



prev_data = -infinity initially

boolean checkBST(node)
{
if(node == null) return true;
if(checkBST(node->left) == false) return false;
if(prev_data > node->data)
{
return false;
}else
{
prev_data = node->data
}
if(checkBST(node->right) == false) return false;
return true;
}

No comments:

Post a Comment