-1

the problem that I have is that for certain keys my function works, but for some it doesn't. The function should return a pointer to the node with the key == givenKey or NULL if there is no element in tree with that key. This is the structure and below is the function.

typedef struct node
{
    int key;
    struct node *l, *r;
}NodeT;

NodeT *search(NodeT *root, int givenKey)
{
    if(root == NULL || root->key == givenKey)
        return root;
    search(root->l, givenKey);
    search(root->r, givenKey);
}

This is the call of the function in main:

    NodeT *q = search(root, 9);
    NodeT *r = search(root, 7);
    printf("%p\n%p\n", q, r);

And this is the given binary tree: (for example q gets the right address, but r will be NULL even though there is an element with key = 7 in our binary tree.

enter image description here

I would really appreciate if you tell me what is wrong, because I tried to change the function a lot of times, but it didn't work. I even looked through my code with the debugger, but it doesn't seem to help that much. Thank you in advance!

1 Answers1

1

Check root if it contains the key, and children recursively. It return NULL if no nodes with the key found.

NodeT* search(NodeT* root, int givenKey)
{
    if (!root)
        return NULL;
    else if (root->key == givenKey)
        return root;

    NodeT* search_child_result = NULL;
    if (root->l)
    {
        search_child_result = search(root->l, givenKey);
        if (search_child_result)
            return search_child_result;
    }

    if (root->r)
    {
        search_child_result = search(root->r, givenKey);
        if (search_child_result)
            return search_child_result;
    }

    return search_child_result;
}
John Park
  • 1,121
  • 8
  • 14