CAP7004 · Unit 5: Trees
AVL trees and rotations
8 practice questions
Key points
- Balance factor = height(left) - height(right) in {-1, 0, 1}
- LL: right rotation; RR: left rotation; LR/RL: double rotation
- All operations O(log n) worst case
- Insert needs at most one (single or double) rotation
An AVL tree is a BST that stays balanced. For every node the balance factor (height of left subtree - height of right subtree) must be -1, 0 or +1. After an insert or delete, if a node's balance becomes +2 or -2, a rotation restores balance. Height stays O(log n), so search, insert and delete are all O(log n) worst case.
| Case | Cause | Fix |
|---|---|---|
| LL (left-left) | Insert into left subtree of left child | One right rotation |
| RR (right-right) | Insert into right subtree of right child | One left rotation |
| LR (left-right) | Insert into right subtree of left child | Left rotation on the child, then right rotation |
| RL (right-left) | Insert into left subtree of right child | Right rotation on the child, then left rotation |
Examples: inserting 10, 20, 30 gives an RR imbalance at 10 (balance -2); a left rotation makes 20 the root with children 10 and 30. Inserting 30, 20, 10 (LL), 10, 30, 20 (RL) or 30, 10, 20 (LR) all produce the same balanced tree with root 20. Inserting 10 to 70 in steps of 10 gives preorder 40 20 10 30 60 50 70.
The smallest AVL tree of height h has N(h) = N(h-1) + N(h-2) + 1 nodes, giving 1, 2, 4, 7, 12, 20 for h = 0 to 5. A perfect tree of 15 nodes has height 3 (4 levels).
Exam pitfall: a single insertion needs at most one rotation (single or double); deletions may need rotations along the path.
Try two questions
Worst-case search time in an AVL tree with n nodes is:
- O(log n)
- O(1)
- O(n log n)
- O(n)
Show the answer
A. AVL height stays logarithmic.
Keys 10, 20, 30 are inserted into an AVL tree. The root afterwards is:
- 30
- 10
- 20
- Not defined
Show the answer
C. A left rotation leaves preorder [20, 10, 30].