Amazon Interview Question
Software Engineer / DevelopersIsBST(Tree *node)
{
return IsBST(node, -infinity, infinity);
}
IsBinarySearchTree(Tree *node, int lower, int higher)
{
if (node == null) return true;
if (node->value < lower || node->value > higher) return false;
return IsBinarySearchTree(node->left, lower, node->value) && IsBinarySearchTree(node->right, node->value, higher);
}
Yes this is the right answer! Same question was asked from me. It was then further extended to find the subtree with maximum number of elements (the given tree need not to be a BST).
Solution of extended part: return integer indicating the number of elements present in the subtree(BST). A negative value will indicate that the subtree contains another subtree (not including itself) of intensity |integer|. If both left and right node returns +ve integers add them and then add 1(including this node) and return a +ve if the node itself follows BST and -ve if the node is not a part of BST.
If your extension question was 'finding the largest subtree which is a BST'...
Take inorder of the given tree and find the longest increasing contiguous sequence.
int FindMax(Tree *root)
- pkm July 31, 2010{
//Assuming root is not null.
if(root==NULL)
return 9999;
while(root->right)
root=root->right;
return root->element;
}
int FindMin(Tree *root)
{
//Assuming root is not null.
if(root==NULL)
return -9999;
while(root->left)
root=root->left;
return root->element;
}
bool isBST(Tree *root)
{
if(root==NULL)
return true;
else if(((root->left!=NULL) && (FindMax(root->left)>root->element))||
((root->right!=NULL) && (FindMin(root->right)<root->element)))
return false;
else
return (isBST(root->right) && isBST(root->left));
}
The idea is to compare root's element with the maximum element in the left subtree and root's element with the minimum element in the right subtree