问题
I would like to free memory from my allocated binary tree what traversal is the best for doing so?
typedef struct Node{
struct Node * right;
struct Node * left;
void * data;
}Node;
typedef int (*cmp) (void*,void *);
Node* init(void * element){
Node * newNode=(Node*)malloc(sizeof(Node));
newNode->data=element;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
void insert(void * element, Node** root,cmp compareTo){
if(*root==NULL){
*root=init(element);
return;
}
if(compareTo(element,(*root)->data)==1)
insert(element,&((*root)->left),compareTo);
else
insert(element,&((*root)->right),compareTo);
}
回答1:
Since it's a tree, you should go with a recursive approach.
deallocate (node):
//do nothing if passed a non-existent node
if node is null
return
//now onto the recursion
deallocate(left node)
deallocate(right node)
free node
回答2:
Think about what the different traversal types do, and keep in mind, after you free memory you're not allowed to access it anymore:
- Preorder: operation performed before visiting any children
- In-order: operation performed after visiting left subtree, before right subtree
- Postorder: operation performed after visiting all subtrees
Given the above statements, the answer should be clear.
回答3:
void free_tree(Node * node){
//post-order like FatalError hinted at
if (node != NULL) {
free_tree(node->right);
free(node->data); //if data was heap allocated, need to free it
free_tree(node->left);
free(node);
}}
A cool way to check seg faults and memory leaks is to use
valgrind --leak-check=full ./yourProgram
回答4:
Depth first search is best for this
回答5:
When you say "best" do you mean "correct" (i.e., won't cause chaos by accessing freed memory) or "most efficient" or what?
As far as correctness goes: Anything you like, provided you take care not to access data after freeing it. The obvious simplest approach (which I won't state explicitly because this looks kinda like homework :-) but it's what you'd do if you wanted to write as little code as possible [EDITED to add: it's what "cnicutar" posted; I hope it wasn't homework after all!]) works just fine.
You might get more efficient results (in space or time) by appropriate matching of the order of freeing with the order of allocation, but the details depend on your memory allocator and you probably shouldn't care.
来源:https://stackoverflow.com/questions/9181146/freeing-memory-of-a-binary-tree-c