1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 5

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.

CaseCauseFix
LL (left-left)Insert into left subtree of left childOne right rotation
RR (right-right)Insert into right subtree of right childOne left rotation
LR (left-right)Insert into right subtree of left childLeft rotation on the child, then right rotation
RL (right-left)Insert into left subtree of right childRight 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

Question 1 · Tier 1, Recall

Worst-case search time in an AVL tree with n nodes is:

  1. O(log n)
  2. O(1)
  3. O(n log n)
  4. O(n)
Show the answer

A. AVL height stays logarithmic.

Question 2 · Tier 2, Understand

Keys 10, 20, 30 are inserted into an AVL tree. The root afterwards is:

  1. 30
  2. 10
  3. 20
  4. Not defined
Show the answer

C. A left rotation leaves preorder [20, 10, 30].