Insert 54 into the AVL tree with root 44, left child 17 (right child 32) and right child 78 (children 50 and 88, where 50 has children 48 and 62). What happens?
54 becomes 62's left child. Walking up, 78 is the first unbalanced node (children of heights 2 and 0): z = 78, y = 50, x = 62. That is a left-right bend, so a double rotation puts 62 on top with 50 and 78 as its children.
* 78 and its ancestor 44 are both out of balance, and one restructuring at 78 fixes both. *
Search path: 54 > 44 (go right), 54 < 78 (left), 54 > 50 (right), 54 < 62 (left): 54 becomes 62's left child.
Heights, walking up:
| Node | Child heights | Height | Balanced? |
|---|---|---|---|
| 62 | 0 (54), −1 | 1 | yes |
| 50 | 0 (48), 1 (62) | 2 | yes |
| 78 | 2 (50), 0 (88) | 3 | no: z |
| 44 | 1 (17), 3 (78) | 4 | no, but higher up |
Restructure: y = 50 (the taller child of 78), x = 62 (the taller child of 50). y is a left child, x a right child: a zig-zag, so a double rotation. Sorted, a = 50, b = 62, c = 78, and the subtrees are T0 = 48, T1 = 54, T2 = empty (62's right), T3 = 88.
Gotcha: T2 is empty here, and it still matters: 62's empty right side becomes 78's left side. A common slip is to hang 54 there, which breaks the order (54 < 62 must stay on 62's left).
Result: 62 takes 78's place, with 50 (children 48 and 54) on the left and 78 (right child 88) on the right. The subtree is back to height 2, so 44's children now have heights 1 and 2 and the whole tree is balanced, without touching 44.