【问题标题】:Printing the words of a trie tree打印三棵树的单词
【发布时间】:2014-05-07 16:48:53
【问题描述】:

我试图在 C 中打印 trie 的内容。但是我不是很成功。也让我在一开始就说,这是我们现在在学校做的事情,这是一个练习。

这就是我的 trie 的样子:

struct node{
    char letter; //holds the letter associated with that node
    int count; //its count
    struct node* child[26]; //each node can have 26 children
};

struct trie{
    struct node* root;
};

这个 print 方法必须遍历这个 trie 并按字母顺序打印单词,不应该打印计数为 0 的单词。

我在考虑递归,这就是我的代码的样子:

void print(node* root) {
    char buffer[15];//array to store the letters
    if(root==NULL){ return;}//if the root is null return
    int i;
    int index=0; //index for the buffer
    int hasAChild=hasChild(root);

    if (hasAChild != 0) { //the root has children keep on going
        for (i=0;i<27;i++) {
            //go thru all the children and if they have children call print                         recursively
            if (hasChild(root->child[i])) {
                print(root->child[i]);
            }
            else {
                // if they have no more children add the letter to the buffer
                buffer[index++] = root->child[i]->letter;
            }
            // print the contents in the bufffer
            printf("%s: %d",root->child[i]->count);
        }
    }
}

// function to determine if a node has children, if so it returns their number if not,returns 0

int hasChild(root) {
    if(root==NULL){
        return 0;
    }

    int i;
    int count=0;
    for(i=0;i<27;i++){
        if(root->child[i]!=NULL){
            count++;
        }
    }
    return count;
}

这就是它的样子

trie 示例:

Root
  +--- a:2
  |     +--- t:4
  |
  +--- b:3
  |     +--- e:5
  |
  +--- c:0

我们有 'a' 2 次,'at' 4 次,'b' 3 次和 'be' 5 次,只应打印单词。 在这个例子中,我将不得不打印 在:4 是:5 但不是 c: 0,因为它的计数是 0

所以我只假设打印形成的单词,而不是不形成单词的字母。任何帮助或指导将不胜感激。谢谢!

【问题讨论】:

  • 旁注:i&lt;27 应该是i&lt;26
  • 恭喜你明确表示这是一项学校练习,而不是试图假装。

标签: recursion c


【解决方案1】:

我在这里看到三个问题:

  • 仅当当前节点没有子节点时,才将字母附加到当前缓冲区。这意味着您将只显示单词的最后一个字母。

  • 另外,每次进入函数,都是从一个空的缓冲区开始的。

  • 您的 printf 语句缺少字符串参数。

您需要传递长度和缓冲区,并确保正确地以空值终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2021-12-11
    • 2013-10-25
    • 2014-07-15
    相关资源
    最近更新 更多