繁体   English   中英

C编程免费特里树

[英]C programming free trie tree

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

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

为了每次将一个文件中的所有单词插入树后都执行此操作,我需要释放树的内存,以便可以将树重新用于下一个文件。 我应该使用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,则尚未释放的内存可能总计很大。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM