Reputation: 1045
This is a node that im using to create a BST. How would I be able to free this tree. Below is an attempt of what I have tried but Im not too sure how to free str.
typedef struct tree_s tree_t;
struct tree_s
{
char *str;
tree_t *left;
tree_t *right;
};
void freeTree(tree_t *tree) {
if (tree == NULL)
{
return;
}
/* first delete both subtrees */
freeTree(tree->left);
free(tree->str);
freeTree(tree->right);
/* then delete the node */
free(tree);
}
Upvotes: 1
Views: 813
Reputation: 30926
Just have a postorder traversal (that is what you are doing) and free()
the memory allocated. [ free(str)
] In your case free(tree->str)
;
You have done it correctly. A more concise one
void preord(tree *root)
{
if(root)
{
preord(root->left);
preord(root->right);
free(tree->str);
free(tree);
}
}
Note: Once you know the node at which you are working currently is non-null then you can free the char *
any time , only remember that the children must be freed before the parent.
Upvotes: 3