问题
I want to remove a binary tree using post-order traversal. Meaning the left part of the tree should be removed first then the right one then remove the whole tree and free memory in a second function that follows after. I'm not allowed to changed the arguments of the function and can only play with the inside of it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "telefonbuch.h"
static inline bstree * create_node(unsigned long phone, char * name)
{
bstree * newNode = (bstree *) malloc(sizeof(bstree));
newNode->key.phone = phone;
strcpy(newNode->key.name, name);
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void bst_insert_node(bstree * bst, unsigned long phone, char * name)
{
if (bst == NULL)
{
return;
}
if (bst->key.phone > phone)
{
if (bst->left == NULL)
{
bst->left = create_node(phone, name);
return;
}
bst_insert_node(bst->left, phone, name);
}
else
{
if (bst->right == NULL)
{
bst->right = create_node(phone, name);
return;
}
bst_insert_node(bst->right, phone, name);
}
}
bst_node * find_node(bstree* bst, unsigned long phone) {
if (bst == NULL)
{
return NULL;
}
if(bst->key.phone > phone)
{
return find_node(bst->left, phone);
}
else if (bst->key.phone < phone)
{
return find_node(bst->right, phone);
}
return &(bst->key);
}
void bst_in_order_walk_node(bst_node* node) {
}
void bst_in_order_walk(bstree* bst) {
int temp = 0;
int level;
while(temp < level)
{
printf("-");
++temp;
}
printf(" (%ld-%s)\n", bst->key.phone, bst->key.name);
if (bst->left != NULL)
{
print_tree(bst->left, level + 1);
}
if (bst->right != NULL)
{
print_tree(bst->right, level + 1);
}
}
void bst_free_subtree(bst_node* node) {
…what goes here?…
}
void bst_free_tree(bstree* bst) {
if(bst==NULL)
return;
bst_free_tree(bst->left);
printf("Deleting %d node.\n",bst->key);
free(bst);
bst_free_tree(bst->right);
}
Here are the structure definitions:
typedef struct _bst_node {
char name[60];
unsigned long phone;
} bst_node;
typedef struct _bstree {
bst_node key;
struct _bstree * left;
struct _bstree * right;
} bstree;
Could you help me finish/correct my code?
回答1:
You have:
void bst_free_tree(bstree* bst) {
if(bst==NULL)
return;
bst_free_tree(bst->left);
printf("Deleting %d node.\n",bst->key);
free(bst);
bst_free_tree(bst->right);
}
This deletes the current node 'in-order', and accesses the freed memory after freeing it. Not good!
You need a close relation:
void bst_free_tree(bstree* bst)
{
if (bst == NULL)
return;
bst_free_tree(bst->left);
bst_free_tree(bst->right);
printf("Deleting %d node.\n", bst->key);
free(bst);
}
This traverses and releases the left sub-tree, then the right sub-tree, and then finally releases the current node.
I don't see a need for the bst_free_subtree()
function; the bst_free_tree()
function frees sub-trees equally well.
来源:https://stackoverflow.com/questions/41334643/c-freeing-memory-of-a-binary-tree-using-post-order-traversal