How does remove work in an AVL tree, and why can it need more than one restructuring?
Remove the key exactly as in a plain binary search tree, then walk up from the parent w of the removed node and restructure at every unbalanced node found. A restructuring after a removal can leave the subtree one level lower than before, which can unbalance an ancestor, so the repairs can cascade up to the root: $O(\log n)$ of them.
The procedure:
- Search for the key and remove its node as in a binary search tree (a node with two children is first replaced by its inorder neighbour, and the neighbour's old node is removed instead).
- Let w be the parent of the node that was actually removed. Walk up from w towards the root.
- At each node that breaks the height rule: restructure, then keep walking.
Note how y is chosen: as z's child in the taller subtree. After an insert that is the side you came up from; after a removal it is the other side, since the side you came from just got shorter, and rotating there would shrink it further.
The difference from insert is the direction of the height change. An insert makes a path one level deeper, and the repair cancels exactly that. A removal makes a path one level shorter. The node above it may now be out of balance because its other side is too deep. Rotating that deep side up fixes this node, but the subtree may end up one level lower than before the removal, and then its parent can be unbalanced in the same way.
| after insert | after remove | |
|---|---|---|
| subtree height after the repair | same as before the update | may be one lower |
| restructurings | at most 1 | up to one per level, $O(\log n)$ |
Each restructuring is still $O(1)$, so remove stays $O(\log n)$ overall.