What are the three kinds of splay step (zig, zig-zig, zig-zag), and when is each one used?
With y as x's parent and z as its grandparent: zig when y is the root (one rotation); zig-zig when x and y are both left or both right children (rotate around z first, then around y); zig-zag when one is a left and the other a right child (rotate around y first, then around z).
* All three end with x on top; the zig-zig and zig-zag steps lift x two levels at once. *
Splaying repeats these steps until x is the root:
while x is not the root:
y = parent(x)
if y is the root: zig
rotate around y
else if x and y are on the same side: zig-zig
rotate around z, then around y
else: zig-zag
rotate around y, then around z
| Step | Situation | Rotations | Result |
|---|---|---|---|
| zig | x is a child of the root | 1, around the root | x is the root |
| zig-zig | x and y lean the same way | 2: around z, then around y | x on top, then y, then z below |
| zig-zag | x and y lean opposite ways | 2: around y, then around z | x on top, y and z as its children |
The zig-zag step is exactly an AVL double rotation. The zig-zig step is not two rotations of x: it first rotates y up over z, and only then x over y. That order matters: it folds the accessed path into a shallower shape, which is what keeps splaying cheap on average.
A zig can only happen as the very last step, because it is only used when x's parent is the root.