AVL trees: insertion and rotations
An AVL tree keeps itself balanced with rotations: subtree heights differ by at most 1.
Rules
- Balance = height left − height right
- Left-left: right rotation; right-right: left rotation
- Left-right and right-left: double rotation
Your turn
Three problems on this topic. Separate lists with commas.
- 1 · AVL tree
- 2
- 3
Insert the numbers one by one into an empty AVL tree.
27, 2, 1, 14, 13, 18
Preorder (comma-separated)
Number of rotations (a double rotation counts once)
Separate lists with commas, such as 3, 5, 7. Spaces don’t matter.
Worked example
Insert the numbers one by one into an empty AVL tree.
6, 38, 18, 17, 31, 22, 30, 1
Worked solution
- 1Rotations: RL(6), R(38)
- 2Preorder: 18, 6, 1, 17, 31, 22, 30, 38
- 3Height: 4
Typical mistake: The rotation happens at the lowest unbalanced node; the left-right case needs a double rotation.
Common questions
Where do you rotate?
At the lowest node whose balance has become ±2.
