Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

Is it actually possible to build this algorithm recursively?

Yes, it's possible to do this using recursion.

You are on the right track. The code just needs a couple of fixes:

  1. The first part of if (id == p->_child[i]->_id)... is completely redundant as it duplicates what the recursive invocation will do anyway (and fails to check wether the child is NULL).
  2. When the function calls itself recursively, the return value is ignored. You need to figure out what to do with that return value.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top