【发布时间】: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<27应该是i<26。 -
恭喜你明确表示这是一项学校练习,而不是试图假装。