【发布时间】:2016-01-18 19:04:30
【问题描述】:
我无法在 C 中打印出 trie 的字词。我已经像这样实现了 trie:
struct trie {
struct trie *children[26];
char letter;
int wordEnd;
};
void printSubtree(struct trie *subtree) {
int i;
if (subtree == NULL){
return;
}
else {
for (i = 0; i<26;i++) {
if (subtree->children[i]!= NULL) {
printf("%c", subtree->children[i]->letter);
printSubtree( subtree->children[i]);
}
}
}
}
void printResult(){
struct trie *temp;
temp = master;
int i ;
if (temp){
for (i = 0; i<26;i++) {
if (temp->children[i]!= NULL) {
printf("%c", temp->children[i]->letter);
printSubtree(temp->children[i]);
printf("\n");
printf("\n");
}
}
}
}
我知道这是不对的,但我不确定如何使用递归来打印单词。如果trie 将"abc" 和"abe" 存储为不同的单词,则最终打印出的只是字符串"abce",将"abc" 和"abe" 插入为不同的单词。
随后,我不确定如何使用DFS打印出来,因为DFS不会一直走到"abc",打印出来,然后回到"b"的级别,看到"b"有一个没有被访问过的孩子,然后打印出来,导致字符串"abce"反正?
【问题讨论】:
-
您可能需要保留表示该单词的整个字符串,并且在下降 trie 时将字母附加到该字符串。当您找到一个单词时,打印该字符串。您不能只打印字母,因为它们只会打印一次,但可能属于多个单词。