algorithm - C - freeing memory of a binary tree using post-order traversal -
i want remove binary tree using post-order traversal. meaning left part of tree should removed first right 1 then remove whole tree , free memory in second function follows after. i'm not allowed changed arguments of function , can play 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 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 me finish/correct code?
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 current node 'in-order', , accesses freed memory after freeing it. not good!
you need 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 , releases left sub-tree, right sub-tree, , releases current node.
i don't see need bst_free_subtree()
function; bst_free_tree()
function frees sub-trees equally well.
Comments
Post a Comment