【发布时间】: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”}。