2017-03-01 53 views
0

我剛開始編程,我有一個初學者的問題:C編程免費特里樹

所以我有一個線索樹,我想用它來從多個文件存儲大量的單詞。

爲了之後我插入所有的話從一個文件到樹這樣做,每次,我需要釋放樹的記憶,這樣我可以重用樹的下一個文件。 我應該使用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; 
}; 
+0

目前尚不清楚你的要求。請提供[mcve]並具體說明您的問題。 – Olaf

+2

如果您分配每個單個節點,則需要釋放(釋放)每個單個節點。每次調用malloc都需要伴隨一個免費的電話。 – Evert

+0

遍歷和自由。 –

回答

0

您必須遍歷樹和自由的每一個節點。您爲Trie創建的每個節點都已動態分配。如果你只是刪除根目錄,然後只對根的內存將被釋放,而對所有其他節點的內存佔用空間在堆中。這意味着你有內存泄漏。如果你爲每個文件創建一個Trie,那麼你沒有釋放的內存可能會增加很多。