【问题标题】:Printing words in a trie in C在 C 中的 trie 中打印单词
【发布时间】:2015-03-28 02:17:46
【问题描述】:

填充 trie 没有问题。单词不包含数字或空格,只包含小写字母。

printTrieContents 使用分配在 main 中的缓冲区。

问题: 如果 trie 包含单词“scores”和“something”,则会打印“scores”,但不会打印“something”。

其他一切都好。

struct trieNode {
  int count;
  struct trieNode *children[ALPHA_SIZE];
};


void printTrieContents(struct trieNode *root, char *buffer, int buffIndex){
        int i;
        for(i = 0; i < ALPHA_SIZE; i++){
                if(root->children[i] != NULL){
                        buffer[buffIndex] = i + 'a';
                        printTrieContents(root->children[i], buffer, buffIndex + 1);
                }
                if(!hasChildren(root)){
                        buffer[buffIndex] = '\0';
                        if(strlen(buffer) > 0){
                                printf("%s: %d\n", buffer, root->count);
                                buffIndex = 0;
                        }
                }   
        }
}

int hasChildren(struct trieNode *root){
        int i;
        for(i = 0; i < ALPHA_SIZE; i++){
                if(root->children[i] != NULL){
                        return 1;
                }
        }
return 0;
}

【问题讨论】:

  • 与问题无关,但你需要在节点中多加一点,否则你将不知道一个词的前缀是否也是一个词。例如:{“a”、“at”、“atrium”}。

标签: c traversal trie


【解决方案1】:

你最终会穿越到一片叶子。在这一点上,作为一片叶子,你没有孩子。你添加 null 并将 buffIndex 设置为零。但是您并没有退出,而是继续旋转,这意味着您将返回该子句并将 buffer[0] 设置为 Null,从而有效地清除您的字符串,您最终将递归备份并继续前进到下一个孩子。

edit:当检测到需要加null,而不是设置buffIndex(注意,buffIndex是当前帧本地的,设置它不会对其余的有任何影响你的调用堆栈)返回。您将开始递归备份您的堆栈。然后你会回到一个有更多孩子的框架,你可以开始迭代其他孩子,用他们的新字符串覆盖缓冲区,并打印新单词。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2017-07-18
    • 2016-05-17
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多