Amazon Interview Question
Software Engineer / DevelopersAargh. Fix formatting.
bool IsBst(Tree *t)
{
return ISBstInternal(t,-infinity, +infinity);
}
bool IsBstInternal(Tree *t, int l, int r)
{
if(!t) return true;
bool l = IsBstInternal(t->left, l, t->value);
bool r = IsBstInternal(t->right, t->value, r);
return l && r;
}
bool verifyTree(Node root){
if(root == null){
return true;
}
Node l = root.getLeft();
Node r = root.getRight();
if(l.getValue() <= root.getValue() <= r.getValue()){
return (verifyTree(l) && verifyTree(r));
}
else{
return false;
}
}
bool isBST(Tree *rt,int val,int flag)
{
if (rt == NULL) return true;
if ( rt->left != NULL)
{
if (rt -> data <= (rt->left)->data) return false;
if(flag ==1 && (rt->left)->data < val) return false;
}
if ( rt->right != NULL)
{
if (rt -> data > (rt->right)->data) return false;
if(flag ==0 && (rt->right)->data >= val) return false;
}
**ignore previous code
bool isBST(Tree *rt,int val,int flag)
{
if (rt == NULL) return true;
if ( rt->left != NULL)
{
if (rt -> data <= (rt->left)->data) return false;
if(flag ==1 && (rt->left)->data < val) return false;
}
if ( rt->right != NULL)
{
if (rt -> data > (rt->right)->data) return false;
if(flag ==0 && (rt->right)->data >= val) return false;
}
return (isBST(rt->left,rt->data,0) && isBST(rt->right,rt->data,1));
}
This can be solved by using recursive approach. For each node, compare its value to left and right child. and "AND" all the possible outcomes. if it returns false for any single node then it is not BST, else BST.
- sur February 03, 2010