Search code examples
cpointersfindbinary-treenodes

How can I return the pointer to a specific node in this Binary Tree?


I have two methods (boolean and pointer return values) for searching for a value in a Binary Tree in C:

bool findInTree(BTNode* bt, char* str) {
    if (bt == NULL) {
        return false;
    }

    if (strcmp(((Course*) (bt->data))->name, str) == 0) {
        return true;
    }

    bool b1 = findInTree(bt->left, str);

    if (b1) {
        return true;
    }

    bool b2 = findInTree(bt->right, str);
    return b2;
}
void* findAndReturnInTree(BTNode* bt, char* str) {
    if (bt == NULL) {
        return (void*) NULL;
    }

    if (strcmp(((Course*) (bt->data))->name, str) == 0) {
        return bt->data;
    }

    void* b1 = findAndReturnInTree(bt->left, str);

    if (strcmp(((Course*) (b1))->name, str) == 0) {
        return b1;
    }

    void* b2 = findAndReturnInTree(bt->right, str);
    return b2;
}

findInTree() works completely fine and is returning the right boolean based on whether that value was in the tree. However, findAndReturnInTree() isn't working and I keep getting segmentation faults. I tried to model it off findInTree() but returning a pointer instead of a boolean. Btw, I am using void pointers as ->data so that I can use multiple structs and have some sort of generic implementation. Can someone please help me with this?


Solution

  • b1, b2 could have NULL value if a tree node is not found.
    After thant b1->name could be segmentation fault.

    Why don't you add to check NULL at b1, b2?
    C Programmer always check Exception cases.

    void* findAndReturnInTree(BTNode* bt, char* str) {
        if (bt == NULL) {
            return (void*) NULL;
        }
    
        if (strcmp(((Course*) (bt->data))->name, str) == 0) {
            return bt->data;
        }
    
        void* b1 = findAndReturnInTree(bt->left, str);
    
        if (b1 == NULL) return findAndReturnInTree(bt->right, str);
    
        if (strcmp(((Course*) (b1))->name, str) == 0) {
            return b1;
        }
    
        void* b2 = findAndReturnInTree(bt->right, str);
        return b2;
    }