0

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.

Lin
  • 966
  • 6
  • 20

1 Answers1

1

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.

Antti Haapala
  • 117,318
  • 21
  • 243
  • 279
  • Yes, true. Thank you very much. Following what you said, but I did slightly different to shorten up: `if(nNode_find(child, val)) return child;`. – Lin Jun 25 '17 at 19:27