所以我發現在網上特里樹的一些例子,除冰嘗試一下,以幫助遊戲IM上的工作將包含在字典中的所有單詞特里樹樹。我在網上找到的例子沒有一個freeTree的任何實現以避免內存泄漏,所以我試圖讓我自己。不過,我有一段時間沒有與C合作過,並且遇到了問題。解放出來特里樹樹
char keys[][8] = {"the", "a", "there", "answer", "any",
"by", "bye", "their"};
char output[][32] = {"Not present in trie", "Present in trie"};
struct TrieNode *root = getNode();
// Construct trie
int i;
for (i = 0; i < ARRAY_SIZE(keys); i++){
insert(root, keys[i]);
}
// Search for different keys
printf("%s --- %s\n", "the", output[search(root, "the")]);
printf("%s --- %s\n", "these", output[search(root, "these")]);
printf("%s --- %s\n", "their", output[search(root, "their")]);
printf("%s --- %s\n", "thaw", output[search(root, "thaw")]);
freeTree(root);
printf("test after free\n");
printf("%s --- %s\n", "the", output[search(root, "the")]);
printf("%s --- %s\n", "these", output[search(root, "these")]);
printf("%s --- %s\n", "their", output[search(root, "their")]);
printf("%s --- %s\n", "thaw", output[search(root, "thaw")]);
這是一個簡單的測試進出口運行和自由後的結果是一樣的前
the --- Present in trie
these --- Not present in trie
their --- Present in trie
thaw --- Not present in trie
test after free
the --- Present in trie
these --- Not present in trie
their --- Present in trie
thaw --- Not present in trie
這裏是使用
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
bool isLeaf;
};
結構IM和自由實現
void freeChildren(struct TrieNode *node){
int i;
if (node->isLeaf == false){
for (i=0;i<ALPHABET_SIZE;i++){
if (node->children[i] != NULL){
freeChildren(node->children[i]);
}
}
}
if (node != NULL){
node = NULL;
free(node);
}
}
void freeTree(struct TrieNode *root){
freeChildren(root);
free(root);
}
瓦我創建一個新的樹節點我malloc它的內存,所以我知道我需要釋放。
感謝您的答覆,現在的作品!意見非常明確,內容翔實,謝謝! – user3267256