Removing Items From A Binary Search Tree
Removing Items From A Binary Search Tree
When removing an item from a search tree, it is imperative that the tree which remains satisfies
the data ordering criterion. If the item to be removed is in a leaf node, then it is fairly easy to
remove that item from the tree since doing so does not disturb the relative order of any of the
other items in the tree.
For example, consider the binary search tree shown in Figure (a). Suppose we wish to remove
the node labeled 4. Since node 4 is a leaf, its subtrees are empty. When we remove it from the
tree, the tree remains a valid search tree as shown in Figure (b).
To remove a non-leaf node, we move it down in the tree until it becomes a leaf node since a leaf
node is easily deleted. To move a node down we swap it with another node which is further
down in the tree. For example, consider the search tree shown in Figure (a). Node 1 is not a
leaf since it has an empty left subtree but a non-empty right subtree. To remove node 1, we swap
it with the smallest key in its right subtree, which in this case is node 2, Figure (b). Since
node 1 is now a leaf, it is easily deleted. Notice that the resulting tree remains a valid search tree,
as shown in Figure (c).