[英]Printing a trie lexicographically in c
所以我正在實現一個特里將單詞存儲在字典文件中。 我已經實現了插入操作; 現在,我正在嘗試印刷。 我快要解決了,但是我有一個小問題,我不確定如何解決。 我還試圖牢記程序的速度,這就是為什么我選擇重選數組或鏈接列表的原因。 這是單個節點的外觀:
struct node {
int end;
int occurrences;
int superwords;
struct node* child[26];
};
“ end”表示單詞的完成(例如,單詞本中字母“ k”的end == 1;這可防止在檢查樹中是否已實際插入單詞時產生混淆)。
方法如下:
void preorder(struct node *follow, char hold[200], int s){
int i = 0;
if(follow == NULL){
return;
}
for(i = 0; i < 26; i++){
if(follow->child[i] == NULL){
continue;
}
else{
printf("%c",'a'+i);
hold[s] = 'a'+i;
s++;
if(follow->child[i]->end == 1){
printf("\n");
hold[s] = '\0';
printf("%s", hold);
}
preorder(follow->child[i], hold, s);
}
}
return;
}
我插入的詞是:噓,書,預訂,約翰,特克斯,文本。 它們應按該順序打印並分隔行。 我的輸出看起來像:
boo
book
booking
bookingjohn
bjohntex
bjtext
bjtext
我知道這可能與我的“ hold”數組有關,該數組存儲單詞的前綴,這樣它們就不會丟失。 我需要在某處將索引設置回零以指示前綴及其所有相關單詞(例如boo,book,booking是一個很好的例子)的完成,但是還沒有成功。 任何幫助將不勝感激,我將很高興進一步闡明我的思考過程。
你很親密
有兩個問題,都存在於遍歷trie分支的for
循環中:
else{
printf("%c",'a'+i);
hold[s] = 'a'+i;
s++;
第一個問題是(幾乎)所有內容都要打印兩次。 在上面的代碼段中,您在跟蹤樹時打印前綴。 然后,當您到達單詞的結尾時,您將打印整個單詞:
if(follow->child[i]->end == 1){
printf("\n");
hold[s] = '\0';
printf("%s", hold);
}
因此根本不需要打印前綴,並且雙重打印令人困惑。
其次, s
參數表示樹中的深度,即當前前綴的長度。 因此在探索特里節點時它應該是恆定的。 但是,每次找到新分支時,都將其遞增(上面第一個代碼段中的s++
)。 而不是這樣做,您需要遞歸調用以使用s + 1
作為其參數,以便將使用正確的前綴長度來調用它。
您還可以相當簡單地簡化控制結構。
這是一個例子:
void preorder(struct node *follow, char hold[200], int s){
int i = 0;
if(follow == NULL){
return;
}
/* Print the word at the beginning instead of the end */
if (follow->end) {
hold[s] = 0;
printf("%s\n", hold);
}
for(i = 0; i < 26; i++){
/* preorder returns immediately if its argument is NULL, so
* there's no need to check twice. Perhaps even better would be
* to do the check here, and not do it at the beginning.
*/
hold[s] = 'a'+i;
preorder(follow->child[i], hold, s + 1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.