Freeing linked structs in C
Okay so I have a Binary Search Tree built using only C structs and pointers because I'm insane and didn't want to use C++. Anyways, I've got some serious memory leaks since I'm assuming free(tree)
, tree being an instance of the struct below, doesn't free all the children of that tree.
Here is my node:
struct node{
struct node* parent;
struct node* left;
struct node* right;
int key; //the value of the node
};
and here is my bst:
struct bst{
struct node* root;
int elements; //number of nodes in the bst
};
So my question, is there any better way of doing this than recursively calling a delete function? for instance (writing this on the spot):
void delete_tree(开发者_如何学运维struct node* n){
if(n == NULL) return;
struct node* left = n->left;
struct node* right = n->right;
free(n);
delete_tree(left);
delete_tree(right);
}
I see absolutely nothing wrong with a recursive delete. You could use an iterative approach, but it wouldn't have any discernible benefits and would be harder to write.
By the way, you can simplify the code a little and remove the two local variables as so:
void delete_tree(struct node* n){
if(n == NULL) return;
delete_tree(n->left);
delete_tree(n->right);
free(n);
}
You are making the recursive calls but never actually call free
. You probably need to verify if a node is a leaf node (maybe asking if both children are null) and call free
on that node.
精彩评论