在n-ary树中搜索项目

时间:2016-05-13 11:49:57

标签: c tree tree-search

我有一个以这种方式组成的树n-ary:

struct n_tree{
    struct list *adj;    
};

struct list{
    struct n_tree *child;
    struct list *next;
    int key;
};

我如何搜索物品? 我已经实现了这个功能,但它不起作用......谢谢!

struct list *find(struct list *root, int key){
    if(root){
        find(root->next,key);
        if (root != NULL){
            if(root->key == key){
                return root;
            }
            else if(root->child != NULL){
                return find(root->child->adj,key);
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您尝试实现的是具有二进制实现(第一个孩子,右兄弟)的n-ary树。

其他命名更明显:

struct n_tree{
  struct list *root;    
};

struct tree_node{
    int key;
    struct tree_node *first_child;
    struct tree_node *right_sibling;
};

递归搜索函数返回带有键的节点,如果没有找到节点则返回NULL可能是:

struct tree_node *find_node(struct tree_node *from, int key){
  // stop case
  if (from==NULL) return NULL;
  if (from->key==key) return from;
  // first we'll recurse on the siblings
  struct tree_node *found;
  if ( (found=find_node(from->right_sibling,key) != NULL ) return found;
  // if not found we recurse on the children
  return find_node(from->first_child, key);
}

如果需要带有n_tree参数的包装函数:

struct tree_node* find(struct n_tree* tree, int key) {
  return find_node(tree->root, key);
}

答案 1 :(得分:0)

查看子项之前,您需要查看本地节点,因为这是您实际找到事物并结束递归的方式。

此外,进行递归调用并忽略返回值是没有意义的(除非有" out-parameter",这里没有)。所以不要这样做。

答案 2 :(得分:0)

以下(可能是最小的)修改代码以实现您的目标:

struct list *find(struct list *root, int key){
    for(; root != NULL; root = root->next){   // scan the siblings' list
        if(root->key == key)                  // test the current node
            return root;                      // return it if the value found

        if(root->child != NULL) {             // scan a subtree
            struct list *result = find(root->child->adj, key);
            if(result)                        // the value found in a subtree
                return result;                // abandon scanning, return the node found
        }
    }
    return NULL;                              // key not found
}