0

This function should return the pointer to the node with value of key, but instead loops over the values until it reaches the value of they key, and returns NULL instead. I'm not sure why.

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

Thanks for your help.

  • 1
    Can you show a [mcve] including how you build your tree and use this function to search it? – Retired Ninja Mar 14 '19 at 00:08
  • what is key? Is it an int or a string or something else? what is queryKey? you haven't given enough info to analyze – bruceg Mar 14 '19 at 00:11
  • Yes, I've updated the function. –  Mar 14 '19 at 00:19
  • 3
    comparing floating point numbers for exact equality is never good... https://stackoverflow.com/questions/1839422/strange-output-in-comparison-of-float-with-float-literal – bruceg Mar 14 '19 at 00:20
  • It seems to have no problem finding the match. It's just looping until it reaches NULL. –  Mar 14 '19 at 00:22
  • 2
    less than and greater than comparisons should be ok... so you will navigate the tree to the right node, it's just that the exact equality test will almost always fail – bruceg Mar 14 '19 at 00:44

1 Answers1

0

I think @bruceg is correctly hinting as to why you are always receiving null. Floating point comparison looking for an exact equality can fail.

Try with these edits:

// 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;
}
BlueStrat
  • 2,202
  • 17
  • 27