What is the balance factor of a node, and how do the balance factors of z and y tell you which rotation to use?
Balance factor = height of the left subtree − height of the right subtree. The AVL rule allows only −1, 0 and +1. At z it is ±2; if y leans the same way as z (same sign, or 0 after a removal), a single rotation fixes it; if y leans the other way (opposite sign), a double rotation is needed.
Annotating each node with its balance factor, written in brackets such as Mozart (+1), is a quick way to trace AVL trees by hand:
| Balance factor | Meaning |
|---|---|
| 0 | both subtrees equally high |
| +1 / −1 | left / right subtree one level higher (allowed) |
| +2 / −2 | left / right side two levels higher: the rule is broken here |
The sign is the direction of the lean, so the case can be read off directly:
| z | y | case | repair |
|---|---|---|---|
| +2 | +1 | left-left | single right rotation around z |
| −2 | −1 | right-right | single left rotation around z |
| +2 | −1 | left-right | left rotation around y, then right around z |
| −2 | +1 | right-left | right rotation around y, then left around z |
| ±2 | 0 | tie (only after a removal) | single rotation |
Gotcha: some sources define it the other way round (right − left), which flips every sign but not the logic: "same sign, single; opposite sign, double" holds either way.