Here is a function to find the lowest common ancestor of a binary search tree.It’s working fine because it print’s the LCA correctly in the function but in the main function it works only if the LCA is equal to the root otherwise returned value is NULL.Can any one explain how?
node* FindLCA(node* root,int val1,int val2)
{
if(root->val<val1&&root->val>val2||root->val>val1&&root->val<val2||root->val==val1||root->v al==val2)
{ cout<<"\n\n"<<"LCA of "<<val1<<"and "<<val2<<"is "<<root->val<<"\n"; //working correctly here
return root;
}
if(root->val>val1&&root->val>val2)
FindLCA(root->left,val1,val2);
else
FindLCA(root->right,val1,val2);
}
int main()
{
int arr[]={5,2,6,1,7,4,8,9};
node* tree=buildtree(arr,8);
printPretty((BinaryTree*)tree, 1, 0, cout);
int a=1,b=2;
node* lca=FindLCA(tree,a,b);
if(lca!=NULL) cout<<"\n\n"<<"LCA of "<<a<<"and "<<b<<"is "<<lca->val<<"\n"; //working only if LCA equals root's value
system("pause");
}
You should
return FindLCA(root->right,val1,val2);instead of just calling it. You only return a value when at root and that is why it is the only case when you get correct output in the main.