i propose a recursive implementation for checking whether binary search tree is valid:
/*
Return true if binary tree is a binary search tree
*/
bool BinaryTree::isBinarySearchTree(BinaryTree* tree, int& prev)
{
if(!isBinarySearchTree(tree->left, tree->data)) // left
return false;
if(tree->value > prev) // here
return false;
else
prev = tree->value;
return isBinaryTree(tree->right); // right
}
i have big doubt on the second check,
if(tree->value > prev) // here
return false;
whats your favorite c++ implementation for this problem?
EDIT
how would you extend to find larger BST in given tree?
It’s amazing how many people get this wrong.
Here’s an example of a tree which the naive solution fails to reject:
Every invocation of a naive check will succeed, since every parent is between its children. Yet, it is clearly not a well-formed binary search tree.
Here’s a quick solution:
This isn’t perfect, because it requires that neither INT_MIN nor INT_MAX be present in the tree. Often, BST nodes are ordered by <= instead of <, and making that change would only reserve one value instead of two. Fixing the whole thing is left as an exercise.
Here’s a demonstration of how the naive test gets it wrong: