gpt4 book ai didi

C - 递归搜索函数找到键然后返回NULL

转载 作者:行者123 更新时间:2023-11-30 16:20:49 25 4
gpt4 key购买 nike

此函数应返回指向具有键值的节点的指针,但会循环遍历这些值,直到到达键的值为止,然后返回 NULL。我不知道为什么。

BST_Node *BST_search(BST_Node *root, int bar, double index){ 
if (root==NULL){
return root;
}

double queryKey=(10.0*bar)+index;

if (queryKey==((10.0*root->bar)+root->index)){
return root;
}
if (queryKey<((10.0*root->bar)+root->index)){
return BST_search(root->left, bar, index);
}
else if (queryKey>((10.0*root->bar)+root->index)){
return BST_search(root->right, bar, index);
}
}

感谢您的帮助。

最佳答案

我认为@bruceg 正确地暗示了为什么你总是收到 null。寻找精确相等的浮点比较可能会失败。

尝试进行以下编辑:

// Your tolerance for equality, may need to adjust depending your use-case
#define EPSILON 0.0000001

BST_Node *BST_search(BST_Node *root, int bar, double index){
if (root==NULL){
return NULL;
}

double queryKey= 10.0*bar+index; // consider passing this as parameter to avoid recomputing on every call
double rootKey = 10.0*root->bar+root->index;
if (queryKey<(rootKey - EPSILON )){
return BST_search(root->left, bar, index);
}
if (queryKey>(rootKey + EPSILON)) {
return BST_search(root->right, bar, index);
}
// Equality is assumed if we reach this code
return root;
}

关于C - 递归搜索函数找到键然后返回NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55152964/

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