BST的最低公共祖先(返回值中的陌生人行为)

Lowest common ancestor of a BST (stranger behavior in returned value)

本文关键字:陌生人 返回值 祖先 BST      更新时间:2023-10-16

这里有一个函数,用于查找二进制搜索树的最低公共祖先。它工作得很好,因为它在函数中正确地打印了LCA,但在主函数中,它只有在LCA等于根的情况下才能工作,否则返回的值为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<<"nn"<<"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<<"nn"<<"LCA of "<<a<<"and "<<b<<"is "<<lca->val<<"n";            //working only if LCA equals root's value
 system("pause");
  }   

你应该return FindLCA(root->right,val1,val2);,而不仅仅是调用它。你只在根目录下返回一个值,这就是为什么当你在main中得到正确输出时,它是唯一的情况。

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<<"nn"<<"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<<"nn"<<"LCA of "<<a<<"and "<<b<<"is "<<lca->val<<"n";  //working only if LCA equals root's value
  system("pause");
}