[英]Printing words in a trie in C
填充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;
}
您最終遍歷了一片葉子。 此時,作為葉子,您沒有孩子。 您附加null 並將buffIndex設置為零 。 但是,您不會退出,而是繼續旋轉,這意味着您將返回該子句並將buffer [0]設置為Null,從而有效地清除了字符串,最終將遞歸並移至下一個孩子。
編輯 :當您檢測到需要附加null時,返回而不是設置buffIndex(注意,buffIndex對於當前幀是本地的,設置它不會對其余調用棧產生任何影響)。 您將開始遞歸備份您的堆棧。 然后,您將返回一個具有更多子代的框架,然后可以開始在其他子代上進行迭代,用他們的新字符串覆蓋緩沖區,並打印新單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.