BST的最低公共祖先(返回值中的陌生人行为)
Lowest common ancestor of a BST (stranger behavior in returned value)
这里有一个函数,用于查找二进制搜索树的最低公共祖先。它工作得很好,因为它在函数中正确地打印了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");
}
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 使用 std::p air 进行返回值优化
- BST的最低公共祖先(返回值中的陌生人行为)