This question was asked to me in an interview: I have a binary tree and I have to find the common ancestor (parent) given two random nodes of that tree. I am also given a point
hi this will return lowest ancestor node value where root of tree and val1,val2 -> data values for nodes are being passed
int CommonAncestor(node *root, int val1,int val2)
{
if(root == NULL || (! root->left && ! root->right )
return false;
while(root)
{
if(root->data < val1 && root->data < val2)
{
root = root->left;
}
else if(root->data > val1 && root->data > val2)
{
root= root->right;
}
else
return root->data;
}
}