Amazon Interview Question
Software Engineer / DevelopersCountry: India
u can modify when calling recursively:
int isBSTUtil(struct node* node, int min, int max) { if (node==NULL) return(false);
if (node->data<min || node->data>max) return(false);
if(node->left)
isBSTUtil(node->left, min, node->data);
if(node->right)
return isBSTUtil(node->right, node->data+1, max);
}
Clasrufy if i made a mistake!
What about creating default parameter with value false ? something like:
int isBSTUtil(struct node* node, int min, int max, bool defaultReturnValue = false);
int isBSTUtil(struct node* node, int min, int max, bool returnValue) { if (node==NULL) return(returnValue);
// false if this node violates the min/max constraint if (node->data<min || node->data>max) return(false);
// otherwise check the subtrees recursively,
// tightening the min or max constraint
return
isBSTUtil(node->left, min, node->data,true) &&
isBSTUtil(node->right, node->data+1, max,true)
);
The easiest way I can think of is indicating if is checking the root or not in the first call.
int isBSTUtil(struct node* node, int min, int max, bool isRoot)
{
if (isRoot && node==NULL)
return false;
else
return true;
}
On the first call on isBST2, isRoot is true. On the recursive calls isRoot is always going to be false.
Your code is not returning result for all scenarios..
consider the case if only a single node tree say 10. It is BST but we are not returning anything so compiler would return an error i guess.
- mr October 19, 2012