这是一个找到二叉搜索树的最低共同祖先的函数。它工作正常,因为它在函数中正确打印LCA但在主函数中它只有在LCA等于root否则返回值时才有效是NULL。可以解释一下吗?
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");
}
答案 0 :(得分:0)
您应该return FindLCA(root->right,val1,val2);
而不是仅仅呼叫它。您只在root时返回一个值,这就是为什么在主要输出正确的情况下它是唯一的情况。
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->val==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)
return FindLCA(root->left,val1,val2); // RETURN VALUE HERE
else
return FindLCA(root->right,val1,val2); // RETURN VALUE HERE
}
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");
}