我目前正在處理一個普通的樹這種結構:如何釋放一棵樹佔用的內存,C?
typedef struct NODE {
//node's keys
unsigned short *transboard;
int depth;
unsigned int i;
unsigned int j;
int player;
int value;
struct NODE *leftchild; //points to the first child from the left
struct NODE *rightbrothers; //linked list of brothers from the current node
}NODE;
static NODE *GameTree = NULL;
雖然是分配不同節點的功能(也懶得在鍵的值太多,基本上分配孩子節點如果沒有任何新的孩子去leftchild,否則它會在列表的末尾「節點 - > leftchild-> rightbrothers」):
static int AllocateChildren(NODE **T, int depth, unsigned int i, unsigned int j, int player, unsigned short *transboard) {
NODE *tmp = NULL;
if ((*T)->leftchild == NULL) {
if( (tmp = (NODE*)malloc(sizeof(NODE)) )== NULL) return 0;
else {
tmp->i = i;
tmp->j = j;
tmp->depth = depth;
(player == MAX) ? (tmp->value = 2): (tmp->value = -2);
tmp->player = player;
tmp->transboard = transboard;
tmp->leftchild = NULL;
tmp->rightbrothers = NULL;
(*T)->leftchild = tmp;
}
}
else {
NODE *scorri = (*T)->leftchild;
while (scorri->rightbrothers != NULL)
scorri = scorri->rightbrothers;
if((tmp = (NODE*)malloc(sizeof(NODE)))== NULL) return 0;
else {
tmp->i = i;
tmp->j = j;
tmp->depth = depth;
(player == MAX) ? (tmp->value = 2) : (tmp->value = -2);
tmp->player = player;
tmp->transboard = transboard;
tmp->leftchild = NULL;
tmp->rightbrothers = NULL;
}
scorri->rightbrothers = tmp;
}
return 1;
}
我需要拿出一個功能,可能是遞歸的,即釋放整棵樹,到目前爲止我已經想出了這個:
void DeleteTree(NODE **T) {
if((*T) != NULL) {
NODE *tmp;
for(tmp = (*T)->children; tmp->brother != NULL; tmp = tmp->brother) {
DeleteTree(&tmp);
}
free(*T);
}
}
但它似乎不工作,它甚至不釋放內存的單個節點。 關於我在哪裏出錯或者如何實施的任何想法? P.s.我已經從我的老師那裏得到了這個僞代碼的遞歸函數的想法。但是我不確定我是否已經用C的類型樹正確地翻譯了它。 僞代碼:
如果我分配大量的樹節點,即會在同一時間消失我喜歡做1: function DeleteTree(T)
2: if T != NULL then
3: for c ∈ Children(T) do
4: DeleteTree(c)
5: end for
6: Delete(T)
7: end if
8: end function