【发布时间】:2016-10-29 23:54:11
【问题描述】:
所以我在网上找到了一些特里树的例子,并尝试将它们用于帮助我正在开发的游戏,该游戏将包含字典中所有单词的特里树。我在网上找到的示例没有任何实现 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")] );
这是我正在运行的一个简单测试,free之后的结果和之前一样
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);
}
当我创建一个新的树节点时,我会为其分配内存,以便我知道我需要释放。
【问题讨论】: