【问题标题】:Printing Contents and Count of Trie in C在 C 中打印内容和 Trie 计数
【发布时间】:2017-11-09 01:00:45
【问题描述】:

我正在编写代码,该代码将打印出 trie 中包含的单词并记录该单词出现的次数。我认为最有效的方法是在将单词添加到 trie 时将字母存储在相关节点的元素中。 Occurrences 基本上是一个表示单词结束的标志,如果它是单词的最后一个字母(表示单词计数),则递增。

此时我的难题是如何让循环检查节点的所有子节点,而不是像现在那样在一条直线上,但我无法想象它是如何工作的。想法?

struct Node{
    char letter;
    struct Node children[26];
    int occurences;
};

printTrie(struct node root){
    int i = 1;
    while(root[i] != NULL){
        fprint(root.letter);
        printTrie(root->children[]);
    }
    i++;
}

【问题讨论】:

  • 那不是有效的 C 代码。 root[i]root 无效,即struct anything,更不用说神秘的struct node,您的代码列表中未提供该struct node。发布真实代码,
  • 这看起来您缺少许多星号 * 指示指针。 struct Node 内不能有 struct Node 数组;宇宙不够大,无法容纳这个结构。您可以拥有一个 struct Node * 数组(指向 struct Node 的指针)。您的函数调用可能也应该采用 struct Node *root — 它目前采用 struct node 的值,但您还没有显示 struct node 的样子,除了它与您显示的 struct Node 无关( C 是区分大小写的语言)。

标签: c pointers recursion printing trie


【解决方案1】:

您要查找的词是recursion,您可以这样做:

if(root != NULL) {
    printf("%c\n", &root->letter);
    printf("%d\n", &root->occurences);
    int i;
    for (i = 0; i < 26; i++) {
        printTrie(root->children[i]); /* <-- Recursion */
    }
}

现在,它将打印根的值首先,然后是每个孩子的值。

如果您希望它在根之前打印每个子项的值,请将 printf 移动到 for 循环之后

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    相关资源
    最近更新 更多