gpt4 book ai didi

c++ - C++ 中的 BST 搜索键

转载 作者:行者123 更新时间:2023-11-30 01:45:37 25 4
gpt4 key购买 nike

我正在尝试实现 BST 搜索方法以在 BST 中查找 key 。下面是代码。

node* search_key(node **root,int key)
{
if (*root == NULL || (*root)->data == key ){
return (*root);
}
if ( key < (*root)->data ) {
search_key(&(*root)->left, key);
}
else{
search_key(&(*root)->right, key);
}
}

除了搜索根节点之外,上面的代码总是返回 null。我将代码修改为以下内容,并且运行良好。谁能解释一下这里涉及的递归?

node* search_key(node **root,int key)
{
if (*root == NULL || (*root)->data == key ){
return (*root);
}
if ( key < (*root)->data ) {
return search_key(&(*root)->left, key); // note return
}
else{
return search_key(&(*root)->right, key);
}
}

最佳答案

在第一个代码片段中,您有一个应该返回某些内容的函数,但在某些情况下不会这样做。这将导致未定义的行为

在第二个片段中,您实际上在函数的所有路径中返回了一些东西。

关于c++ - C++ 中的 BST 搜索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34327600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com