Search code examples
ctreen-ary-tree

Find element in a n-Ary tree


Given the following structure

struct nNode {
   int val;
   struct nNode parent;
   struct nNode children;
   struct nNode next;
   struct nNode prev;

};

Where the children points to first child and to traverse to the other childs we need to follow node->children->next ...

I'm trying to return a pointer to the element that contains some val using the function

struct nNode* nNode_find(struct nNode *node, int val)
{
  // We found the node return the pointer
  if(node->val == val) return node;
  // We didn't found let's check the children
  struct nNode *child = node->children;
  while(child) {
    nNode_find(child, val);
    child = child->children;
    // We didn't found on child, lets check his brothers
    struct nNode *sibling = child->next;
    while(sibling) {
      nNode_find(sibling, val);
      sibling = sibling->next;
    }
  }
  // We didn't found the element return NULL
  return NULL;
}

Given a tree calle TREE like:

  /*                      1
   *            /---------|--------\
   *          2           3         4
   *        /   \                 /
   *      5       6              7
   */

A command like

struct nNode *ptr = nNode_find(TREE, 3);

should return a pointer to root->children->next , but with actual nNode_find is returning NULL.


Solution

  • The problem is that you're ignoring the return value from recursive nNode_find. If the value returned is non-NULL, you should return it outright. So instead of

    nNode_find(child, val);
    

    do

    struct nNode* found = nNode_find(child, val);
    if (found) {
        return found;
    }
    

    Also, each nNode_find invocation should just handle one node, not descend to childrens children, or so; you'd want to do some debug prints to make sure that each node is searched at most once and only once.