I have a tree defined like,
struct tree {
char label[MAX_LENGTH];
char value[MAX_LENGTH];
struct tree *child;
struct tree *next;
};
Now I need to free the memory allocated by this tree. I wrote the following code.
unsigned int tree_free(struct tree *root)
{
struct tree *current = NULL, *next = NULL, *child = NULL;
unsigned int freecnt = 0;
current = root;
while(current != NULL)
{
next = current->next;
child = current->child;
xfree(current);
freecnt += tree_free(child) + 1;
current = next;
}
return freecnt;
}
This method returns the number of items it freed so that I can verify it against the number of allocations made. This code works. But I am not sure this is the correct way of doing things.
This is a suffix tree implementation. For items s,stack,over, overflow, stackoverflow the tree will look like
root
-s
--stack
---stackoverflow
-over
--overflow
Any suggestions to improve the code are welcome.