首页 > 解决方案 > C - 递归搜索函数找到键然后返回 NULL

问题描述

这个函数应该返回指向具有 key 值的节点的指针,而是循环遍历这些值,直到它到达它们的 key 值,然后返回 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);
    }
}

谢谢你的帮助。

标签: crecursionsearch

解决方案


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

尝试以下编辑:

// 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;
}

推荐阅读