330 Intermediate C Programming
TreeNode * lc = tn -> left;
34
free (tn);35
return lc;36
}37
// tn have two children38
// find the immediate successor39
TreeNode * su = tn -> right; // su must not be NULL40
while ((su -> left) != NULL)41
{42
su = su -> left;43
}44
// su is tn’s immediate successor45
// swap their values46
tn -> value = su -> value;47
su -> value = val;48
// delete su49
tn -> right = Tree_delete(tn -> right , val);50
return tn;51
}52
After swapping the values, Fig. 20.11 (a) is temporarily not a binary search tree. This is
because the value “8” is now on the right side of “9”, a violation of the binary search tree’s
properties. When “8” is deleted, then the tree becomes a binary search tree again.
A common mistake at line 49 is calling Tree
delete(tn, val). This is wrong because
“8” is smaller than “9”. Using Tree
delete(tn, val) causes the function to search for
(and attempt to delete) “8” from the left side of “9”. Since “8” is not on the left side, the
function will fail to do anything. If nothing is deleted, the function returns the root tn and
this line becomes tn -> right = tn. A node that is its own parent creates many problems
and furthermore all nodes to the right side (“8”, “11”, and “12”) are lost.
Another common mistake is to write while (su != NULL) at line 40. The while loop
will continue until su is NULL, and the program will have segmentation fault at line 46 when
it attempts to read su -> value.
20.6 Destroying a Binary Search Tree
The Tree destroy function destroys the whole tree by releasing the memory occupied
by all the tree nodes.
// treedestroy.c
1
#include "tree.h"2
#include <stdlib.h>3
void Tree_destroy(TreeNode * n)4
{5
if (n == NULL)6
{7
return ;8
}9
Tree_destroy(n -> left);10
Tree_destroy(n -> right);11