[英]How to find the height of a trie tree in C
我很難編寫算法來找到特里樹的高度。 我不知道如何開始或如何做。 抱歉,如果這是一個“菜鳥”問題,但是我很想嘗試,這是我分配的唯一缺少的部分。
無論如何,這是特里樹的結構:
typedef struct RegTrie * ImplTrie;
typedef struct RegTrie {
Boolean IsItAWord; /* true if it is a word, false if it is not a word */
ImplTrie children[ALPHABETsize];
} RegTrie;
因此,基本上,如果“ a”是一個孩子,則chidren [0]中將有一個Trie;如果“ b”不是孩子,則children [1]將為NULL。 如您所見,這些字符是由鏈接索引隱式定義的,並且如果過去節點的字符組成一個單詞直到當前節點,“ Boolean IsItAWord”將為true。
你們能給我個啟示嗎? 我唯一知道的是,高度可以由最長單詞的長度+ 1定義。但是我不知道該怎么做。 我真的只是想要一個解決方案,因此,找到此高度的任何方法將不勝感激。
謝謝。
您可以使用采用ImplTrie
並返回int
的遞歸函數來完成此操作。
基本情況檢查ImplTrie
是否為NULL
,在這種情況下,該函數返回0
。
否則,該函數將遍歷children
循環,調用自身,選擇最大值,然后返回最大值加1。
int height(ImplTrie t) {
if (!t) return 0;
int res = 0;
for (int i = 0 ; i != ALPHABETsize ; i++) {
int h = height(t->children[i]);
if (h > res) {
res = h;
}
}
return res + 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.