What is trinode restructuring, and why do the four rotation cases all end in the same shape?
Rename x, y and z as a, b, c in sorted order and their four hanging subtrees as T0 to T3 from left to right. Every case ends with b on top, a and c as its children, and T0, T1, T2, T3 attached left to right.
* Four different starting shapes, one target: the middle key on top. *
The four cases (left-left, right-right, left-right, right-left) look like four algorithms, but they are one:
- Sort the three nodes by key: a < b < c.
- List the subtrees that hang off them, in inorder: T0, T1, T2, T3.
- Build: b is the new subtree root, a its left child with T0 and T1, c its right child with T2 and T3.
This works because a binary search tree is fully determined by its inorder sequence and its shape. The inorder sequence T0, a, T1, b, T2, c, T3 cannot change (it is the sorted order of the keys), so the only freedom is the shape, and the balanced shape is "middle on top".
Self-check after every rotation: read the subtree in inorder. If the keys are no longer sorted, a subtree was hung in the wrong place.
Whether that takes one or two rotations depends only on who is b:
| b is | shape | rotations |
|---|---|---|
| y | straight line (left-left or right-right) | single |
| x | zig-zag (left-right or right-left) | double |
Go deeper:
AVL tree — rebalancing — the same four cases with the single and double rotations spelled out.