C 编程免费的特里树

Woshidashen

我刚开始编程,我有一个初学者问题:

所以我有一棵特里树,我想用它来存储来自多个文件的大量单词。

为了在每次将一个文件中的所有单词插入到树中后都这样做,我需要释放树的内存,以便我可以将树重用于下一个文件。我应该使用 free 来释放根吗?或者我需要遍历树并一一删除所有节点?

这是节点,我已经能够将所有单词插入树中。

struct node{
struct node * parent;
int noempty;
int isword;
int super;
int occurrence;
int leaf;
struct node * child[26];
};

这是我的插入函数:

struct node* insert(struct node *root,char *c){
int i=0;
struct node *temp=root;
int l=length(c);
while(i!=l){
int index=c[i]-'a';
if(temp->child[index]==NULL){
//New Node
struct node *n=(struct node *)malloc(sizeof(struct node)); 
n->parent=temp;
temp->child[index]=n;
temp->noempty=1;
}
//Node Exist
if(i!=l&&temp->leaf==1){temp->leaf=0;}
temp=temp->child[index];
i++;
}
if(temp->noempty==0){
temp->leaf=1;}
temp->isword=1;
return root;
};
布兰登巴斯比

您必须遍历树并释放每个节点。您为 Trie 创建的每个节点都已动态分配。如果你只是删除根,那么只会释放根的内存,而其他每个节点的内存都会占用堆中的空间。这意味着您有内存泄漏。如果您为每个文件创建一个 Trie,您尚未释放的内存可能会增加很多。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章