在n-Ary树中查找元素

时间:2017-06-25 19:04:55

标签: c tree n-ary-tree

给出以下结构

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

};

如果children指向第一个孩子并且要遍历其他孩子,我们需要关注node->children->next ...

我尝试使用函数返回指向包含某些val的元素的指针

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;
}

给定树TREE,如:

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

这样的命令
struct nNode *ptr = nNode_find(TREE, 3);

应返回指向root->children->next的指针,但实际nNode_find正在返回NULL

1 个答案:

答案 0 :(得分:1)

问题是你忽略了递归nNode_find的返回值。如果返回的值为非NULL,则应该直接返回。而不是

nNode_find(child, val);

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

此外,每个nNode_find调用应该只处理一个节点,而不是下降到儿童的子节点,或者等等;你想做一些调试打印,以确保每个节点最多只搜索一次。