Home > Back-end >  C binary tree search
C binary tree search

Time:03-16

I'm trying to find node in binary tree, but the function returns nothing, NULL! By the way, in printf, in

if ((cond = strcmp(head->word, word_to_search)) == 0)

the result is right, it just does not return value, probably I'm making it wrong with recursion, I don't know. By the way if I wrap last return NULL in else, it does return valid pointer, but it causes a warning...

struct count_tree *
binaryt_search(struct count_tree *head, char *word_to_search)
{
    int cond = 0;
    if (head != NULL) {
        if ((cond = strcmp(head->word, word_to_search)) == 0) {
            printf("Found %s %d\n", head->word, head->count);
            return head;
        }
        else if (cond < 0) {
            binaryt_search(head->left, word_to_search);
        }
        else {
            binaryt_search(head->right, word_to_search);
        }
    }
    return NULL;
}

CodePudding user response:

You need to return the results of the calls to binaryt_search(). So,

binaryt_search(head->left, word_to_search);

becomes

return binaryt_search(head->left, word_to_search);

and

binaryt_search(head->right, word_to_search);

becomes

return binaryt_search(head->right, word_to_search);
  • Related