【问题标题】:Search for an item in an n-ary tree在 n 叉树中搜索项目
【发布时间】:2016-05-13 11:49:56
【问题描述】:

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

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

【问题讨论】:

  • 如何在n 节点之间分割键范围?我的意思是,使用二叉树很简单:key 下方的所有内容都向左,其他所有内容都在右侧。但是使用n 元素就不太清楚了。
  • 您进行了递归调用find(root->next,key);,但从不使用返回的结果。那你为什么打这个电话?
  • 你说你有一个'以这种方式组成的树',但实际上你没有显示任何'way'。您刚刚展示了数据结构,但没有解释它们的含义:列表是否以某种方式排序?与next 链接的列表中keys 之间的关系是什么?列表项中的keychild 子树中的child 之间的关系是什么?
  • 因为我需要使用返回递归调用来访问树。
  • 节点不排序,一个父节点由一个子节点列表组成,列表的第一个节点是父节点的第一个子节点

标签: c tree tree-search


【解决方案1】:

看来您要实现的是具有二进制实现(第一个孩子,右兄弟)的 n 叉树。

其他命名更明显:

struct n_tree{
  struct list *root;    
};

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

如果没有找到节点,则返回具有键 key 或 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);
}

【讨论】:

    【解决方案2】:

    在查看子节点之前,您需要查看本地节点,因为这就是您真正查找事物并结束递归的方式。

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

    【讨论】:

      【解决方案3】:

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

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-23
        • 1970-01-01
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 2010-10-26
        • 2021-12-26
        相关资源
        最近更新 更多