When an AVL tree is out of balance after an update, how are the three nodes z, y and x of the repair chosen?
z is the lowest node that breaks the height rule, found by walking up from where the change happened; y is z's child on the taller side, and x is y's child on the taller side.
The repair always works on exactly three nodes and the (up to four) subtrees hanging off them:
- z: walk from the inserted node (or the removed node's parent) towards the root, recomputing heights. The first node whose children differ in height by 2 is z. Only nodes on that path can be affected, because no other subtree changed; and z is always the topmost of the three nodes.
- y: the child of z with the greater height, the side that grew too tall.
- x: the child of y with the greater height, one more step into the heavy side.
Choosing "the taller child" twice means z, y and x lie exactly along the path that made the tree too deep, and that is the path the rotation must shorten.
Gotcha: why the lowest unbalanced node? Several ancestors can be out of balance at once (inserting 54 three levels below 78 can unbalance both 78 and its ancestor 44). Repairing the lowest one restores its subtree's old height, and with it the balance of everything above. Starting higher up would rotate the wrong part of the tree.
Gotcha: ties. After a removal, y's two children can have the same height. Then x is the child on the same side as y (left child if y is a left child). That picks a single rotation, which is always safe; a double rotation might leave the tree unbalanced.