Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Here is my code...
bool IsPresent(Tree *root, int value)
{
if(root != NULL)
{
if(root->data == value)
return true;
else return (IsPresent(root->left, value) || IsPresent(root->right, value));
}
return false;
}
void FirstCommonAncestor(Tree *root, int lValue, int RValue)
{
if(root == NULL)
{
}
else
{
if(IsPresent(root->left, lValue) && IsPresent(root->right, RValue))
{
printf("Ancestor %d", root->data);
}
else
FirstCommonAncestor(root->left, lValue, RValue);
FirstCommonAncestor(root->right, lValue,RValue);
}
}
Essentially what you are doing here is for finding common ancestor on the binary search tree (BST) but not for binary tree in general. For regular binary tree you need to call checkValue() on both a and b on the given node (either left or right from the root), from there you can determine whether a and b are fall between root or not. Otherwise, you need to continue recursively on one of the child of the root.
- Anonymous March 23, 2012