【问题标题】:print all words of a dictionary using trie使用 trie 打印字典的所有单词
【发布时间】:2017-07-18 20:40:35
【问题描述】:

我正在使用带有 c 中以下结构的 trie 编写字典

  struct trie_node {
    int is_end;   //0 is is not the end of the word ,otherwise 1
    char c;       
    struct trie_node* child[26];
  };

我能够插入单词、搜索单词,并且我想打印字典中的所有单词。不知道如何处理。我正在尝试打印

void print(struct trie_node node) {
int i = 0;
 for (i = 0; i < 26; i++) {
    if (node->child[i] != NULL) {
       printf("%c", node->child[i]->c);
       print(node->child[i]);
    }
 }

}

但打印不正确 例如,如果我有的话 啤酒 蜜蜂 熊 野兽

正在打印 熊熊 它应该打印 熊熊蜂啤酒

如何正确打印单词列表?

【问题讨论】:

  • 当您递归调用print(node-&gt;child[i]); 时,您不会打印祖先节点中的任何字符。所以在打印bear 之后,您的程序会在beast 的末尾打印st,而不重复前三个字符。
  • 您没有提供足够的信息让我们重现您描述的问题;尝试将您的 exampleEnglish 移动到 CC++ (并确保它可以编译和运行,这样我们就可以重现您描述的问题)...另一件事是,您需要选择一种语言; C 或 C++。如果您的代码使用 C 编译器编译,您可以选择 C。否则,选择 C++。
  • @zancudo,请在下面查看我的答案,如果您尝试过,请告诉我。

标签: c++ c trie


【解决方案1】:

你可以尝试使用node.child[i]->c,使用struct var时必须使用“.”,使用struct point时必须使用“->”或“(&point).”,我不'不知道我的想法是真的:)

【讨论】:

    【解决方案2】:

    您需要跟踪路径(从根到当前节点的路径)。当您到达一个结束节点(is_end 为真)时,您打印作为字典单词的路径。

    一种方法是使用char 的数组并跟踪其长度,以便知道需要打印多少元素。请看下面的代码:

    void print_path (char *path, int len){
      int i;
      for(i = 0; i < len; i++)
        printf("%c", path[i]);
    }
    void print(struct trie_node* node, char *path, int len) {
      // sanity check
      if (! node)
        return;
    
      // current node is part of the current path, so add it
      path[len++] = node->c;
    
      // if it is an end node then print the path
      if (node->is_end)
        print_path(path, len);  
    
      // now go through the children and recursive call 
      int i = 0;
      for (i = 0; i < 26; i++) {
        if (node->child[i] != NULL) {
          print(node->child[i], path, len);                     
        }
      }
    }
    
    int main(){
      // proper allocation for the trie
      // ...
      // calling the print, assuming the height of tree is at most 128
      char path[128];
      print(b, path, 0);
    }
    

    【讨论】:

    • 另外,我建议您考虑stop casting malloc in Cstop using malloc in C++,考虑sizeof (char)(回顾int len 的类型和回顾malloc(128 * 1) 的价值)和什么时候最适合使用自动存储持续时间而不是动态分配(malloc/freenew/delete,无论您选择什么)...
    • 当人们转换malloc的返回值而不是free的参数时,我总是感到惊讶;这将把malloc 抛到窗外的整个推理都彻底颠覆了。因此,您需要演员在 C++ 中将 void * 转换为 char *,但您不需要反过来吗?嗯...
    • 感谢您指出这一点(malloc 不需要强制转换)。
    • 最后,由于分配大小是固定的,所以我删除了 malloc 分配。
    • 是的,您选择了自动存储期限...不错的选择:)
    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 2022-11-25
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多