簡體   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