The key is deleted from an interior node: In this case we find the
smallest key in the key's right subtree (the BTree notes call this key the
key's successor), much like we did when we deleted a key from a Binary
Search tree node that had two children. We first delete this smallest
key, which must be in a leaf, and then replace the deleted key with
this smallest key. Note that this case is very similar to the two child
deletion case in a Binary Search tree. Also note that the
BTree notes
immediately replace the deleted key with its successor, rather than waiting
until the successor has been deleted. Either approach is fine.
As an example, the
BTree notes
delete C from a B-tree of order 5. The smallest key in C's right subtree
is D, so we first delete D from the tree. The notes immediately replace
C with D and remove D from its leaf. This requires us to merge
D's leaf with its left sibling. We must also add AB and DE's parent to
the merged node. This parent is D, since it replaced C. Thus we
also add D to the merged node, creating
a node with A, B, D, and E. Now we consider the parent, which is F.
Its right sibling, MRU, can spare a key, so F's parent, J, moves down
and joins F and M moves up to the parent. We also have to move M's
left child over so that it becomes a right child of J. Notice that this
is a bit like the rotation that we discussed with AVL trees. In this case
we are doing a quasi-rotation about M.
As a final example, suppose we delete the root M from the last example
tree shown in the BTree notes.
The smallest key in M's right subtree is N, so we replace M with
N. This leaves NP with only 1 key, P. P's right sibling cannot spare a
key, so we must merge P with ST. This also requires that the parent of
P and ST, R, be moved into the merged leaf, producing the leaf PRST:
N
----------------
| |
F J U
------------ ---------
| | | | |
ABDE GI KL PRST XZ
U's node now does not have the minimum required number of keys and its
left sibling, FJ, cannot spare one. Hence we merge FJ with U and include
their parent, N, in the merged node. The new node contains the keys FJNU.
We now have a tree with one less level:
-------------------------
| F J N U |
-------------------------
/ | | | \
| | | | |
ABDE GI KL PRST XZ