## 7.14.Deleting an Element from a BST

Deleting an element x from a BST is a little more complicated than lookup or insert. To begin, we may locate the node n containing x. If their is no such a node we are done. If n is a leaf we can simply delete the leaf. If x is at an interior node n, we cannot delete that node, because to do so would disconnect the tree.

We must rearrange the tree in some way so that the BST property is maintained and yet x is not longer in the tree. There are two cases:

First, if n has only one child, we can replace n by that child.

Second, n has two children present. One strategy is to find the node m with label y, the smallest element in the right subtree of n, and replace x by y in node n and remove the node m (see first).

The algorithm as a Nassi Shneidermann diagram:

Procedure deleteElement(node n_r, label x):

Procedure delete_min(node root): label

Examples:

• Delete the nodes with the labels from the table I, II, III from the following tree:

```I.     20, 19, 33, 22, 12
II.    16, 17, 3
III.   12, 13, 22, 16
```
• Delete the nodes with the labels from the table I, II, III from the following tree:

```I.     -3, -2, 22, 8
II.    12, 6, 8, 9
III.   17, -3, 22, 33, 8, -1
```