C 编程自由特里树

C programming free trie tree

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

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

为了每次将一个文件中的所有单词插入树后执行此操作,我需要释放树的内存,以便我可以为下一个文件重用树。 我应该使用 free 来释放 root 吗?或者我需要遍历树,将所有节点一一删除?

这是节点,我已经可以将所有单词插入树中了。

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 创建的每个节点都是动态分配的。如果你只是删除根,那么只有根的内存会被释放,而其他每个节点的内存都会在堆中占用 space。这意味着你有内存泄漏。如果您为每个文件创建一个 Trie,您尚未释放的内存加起来可能会很大。