How is a node with two internal children removed? Give the example remove(6) in the tree 6 → (2, 9), 2 → (1, 4), 4 → (external, 5), 9 → (8).
Find w, the inorder predecessor of v (the largest key in v's left subtree), copy w's entry into v, then delete w with removeExternal(z) on w's right child z, which is always external. Removing 6 puts 5 into the root.
- Find the predecessor w: go to v's left child once, then right as far as possible. From 6: left to 2, right to 4, right to 5, whose right child is external. So w = 5.
- Copy key and value of w into v: the root now holds 5.
- Delete w by calling
removeExternal(z)on w's right external child z. w now has at most one internal child, so this is case 1 or case 2.
Result: 5 → (2, 9), 2 → (1, 4), 9 → (8). Inorder: 1, 2, 4, 5, 8, 9.
Why not something simpler? Deleting the node 6 outright would split the tree into two parts. Pulling its child 2 up into its place would give 2 three children (1, 4 and 9). Neither works.
The invariant to keep is the inorder order. Write it out: 1, 2, 4, 5, 6, 8, 9. Whatever replaces 6 must keep the remaining keys in that order, so only its direct inorder neighbours qualify: 5 (the predecessor) or 8 (the successor). Between copying 5 into the root and deleting the old 5, the tree briefly holds the key twice; that is fine, because the remove operation has not finished yet.
Why the predecessor? v needs a replacement key that fits between its two subtrees. The predecessor is the largest key smaller than or equal to key(v), so it is ≥ everything else in the left subtree and ≤ everything in the right subtree: placed at v, it satisfies the ordering property on both sides.
Why is w easy to delete? It is the rightmost node of the left subtree; if it had an internal right child, that child would be larger and w would not be the rightmost. So w's right child is external, and w falls under case 1 or 2.
The mirror image works too: the inorder successor (smallest key in the right subtree) can replace v in the same way.
* Copy the predecessor's key into v, then delete the predecessor, which has an external right child. *
Go deeper:
Open Data Structures 6.2: an unbalanced binary search tree — complete Java code for find, add and remove, including the two-children case.