私はトライ木の例をいくつか見つけ出し、辞書にあるすべての単語のトライ木を含むゲームを手伝うためにそれらを試してみました。私の例では、メモリリークを避けるために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;
};
を用いた構造イムとフリーな実装である
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私は新しいツリーノードを作成します。私はそのためにメモリをmallocします。私は自由にする必要があることを知っています。
応答いただきありがとうございます!コメントは非常に明確で有益でしたありがとう! – user3267256