Frage

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;
}
War es hilfreich?

Lösung

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

Andere Tipps

You always return the root which is never made NULL. Replacing the root->left = and root->right = with simple returns should help.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top