Итак, я нашел несколько примеров trie trees на линии и сделал все возможное, чтобы попробовать их, чтобы помочь игре, в которой работаю над этим, будет содержать дерево trie из всех слов в словаре. В примере, который я нашел на линии, не было никакой реализации freeTree, чтобы избежать утечек памяти, поэтому я пытаюсь сделать свой собственный. Однако я не работал с c в то время, и я сталкиваюсь с проблемами.Освобождение trie tree
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;
};
и свободная реализация
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);
}
Wh ru Я создаю новый узел дерева i malloc память для него, поэтому я знаю, что мне нужно освободить.
Спасибо, что ответ работает прямо сейчас! Комментарии были очень четкими и информативными спасибо! – user3267256