c - 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);
}
}
谢谢你的帮助。
解决方案
我认为@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;
}
推荐阅读
- javascript - 如何处理模板文字中缺少的嵌入表达式
- powerbi - 在一个 Power BI 可视化中应用顶部和底部 N
- python - 可以使用 [:1] 代替 [0] 吗?
- javascript - 将色调状态值插入 Chromajs HSL 状态值
- pandas - 如何在保持宽度的同时减少 barh 图之间的空间
- react-native - 如何在 xcworkspace 项目中使用“increment_build_number”?
- sql - 从 2 个表创建视图,其中一个表优先于另一个表(除了一个 col 之外,两个表大多相似)
- typescript - 如何声明返回自己原型的 TypeScript 函数类型?
- azure - 上传到块 blob 时使用 UploadFromStreamAsync 和 DownloadToStreamAsync 时数据如何分块
- java - 如何根据 data-stat 从表中获取 1 个元素