Search code examples
csearchtreemultiway-tree

Multiway Tree search algorithm in C implementation


typedef struct dt {
    .....;
} Data;

typedef struct nd {
    int id;
    Data *data;
    struct tm *_parent;
    struct tm *_child[7];
} Node; 


Node* findNode(int id, Node *tree) {
    Node *p = tree;
    if (id == p->_id)
        return p;
    for (int i = 0; i < 7; i++) {
        if (id == p->_child[i]->_id) {
            p = p->_child[i];
            break;
        } else if(p->_child[i] != NULL) {
            findNode(id, p->_child[i]);
        }
    }

    return p;
}

I have a multi-way tree for which every node consists of 0-7 children. Children may be added and removed in no particular order. I am trying to build a search algorithm that given an id will search the tree and return a pointer to the particular node. I have tried to do it recursively as above, without much luck. Is it actually possible to build this algorithm recursively or do I also need to use a stack?


Solution

  • There are some problems with your end conditions. If the loop doesn't find the id, it must be detectable through the return value. Making it NULL in that case would be sensible. This can be done by making two changes: instead of setting p and doing break, return it directly (that way the for loop will only finish if the id is not found), and change return p at the end into return NULL.

    Then when making the recursive call, you need to check the return value. If it was NULL, continue. Otherwise return it.

    And the previous answer is correct that the check for the child id can better be removed, too, especially because it needs to (but doesn't) check for NULL.