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

标签 c recursion search

此函数应返回指向具有键值的节点的指针,但会循环遍历这些值,直到到达键的值为止,然后返回 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/

相关文章:

c++ - 递归函数,它在 C++ 中的数组( vector )中写入整数?

java - Elasticsearch : How to get score for each word matched in a match query

c - 将来自 strtok() 的 token 存储在双指针 "2d array"中

c - C 中的堆栈粉碎/缓冲区溢出

java - BST 的共同元素

jquery - AJAX 从 Twitter 搜索读取 JSON 数据不起作用

javascript - 将所有类型的语言转换为一种语言以进行比较

c - 如何在 C 中读取二维数组?

c - 如何在GCC编译器上的c程序中使用.lib文件方法

python - 使用Python递归替换字符串中的字符