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);
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With