Reputation: 1097
I am trying to search for a number in a BST and the function is always printing "YES" (Number was found)
Here is the code I have in main
printf("Enter a number to search: ");
scanf("%d", &num);
if (search(root, num) != NULL) {
printf("YES\n");
}
else {
printf("NO\n");
}
And here is my search function
BST* search(BST* root, int value) {
if( root == NULL) {
return NULL;
}
else if(value < root->value) {
root->left = search(root->left, value);
}
else if(value > root->value) {
root->right = search(root->right, value);
}
return root;
}
Upvotes: 0
Views: 75
Reputation: 718
I don't really get, why you overwrite root->left
or root->right
. I think your search()
function should look like this:
BST *search(BST *root, int value)
{
if (root == NULL)
return NULL;
if (value == root->value)
return root;
if (value < root->value)
return search(root->left, value);
if (value > root->value)
return search(root->right, value);
return NULL; /* not actually reached */
}
Upvotes: 2
Reputation: 747
You always return the root which is never made NULL. Replacing the root->left =
and root->right =
with simple return
s should help.
Upvotes: 1