An AVL tree is a BST that keeps itself balanced after every insertion and deletion, so its height is always O(logn). It was the first such tree, invented by Adelson-Velsky and Landis in 1962.
Balance
The balance factor of a node is bf=h(right)−h(left) (some books use left − right). In an AVL tree every node has bf −1 (left-high), 0 (balanced) or +1 (right-high). After an insertion or deletion a node may reach ±2; a rotation then repairs it.
An AVL tree with n nodes has height less than about 1.44log2(n+2), so search, insertion and deletion are O(logn) in the worst case.
Rotations
A rotation changes the shape of a small part of the tree but keeps the inorder (sorted) order of the keys. Let k be the lowest node with bf =±2. The four cases are named after the path from k to the inserted node:
Case
Where the new node went
Fix
LL
Left subtree of k‘s left child
Single right rotation at k
RR
Right subtree of k‘s right child
Single left rotation at k
LR
Right subtree of k‘s left child
Left rotation at the child, then right rotation at k (double rotation)
RL
Left subtree of k‘s right child
Right rotation at the child, then left rotation at k (double rotation)
Single right rotation (LL case) at k2
k2 k1 / \ / \ k1 C ==> A k2 / \ / \ A B B C(A is too tall) (B moves across to k2)
The left rotation (RR case) is the mirror image. A double rotation is two single rotations: for LR, first rotate left at k2‘s left child, which turns the bend into a straight line, then rotate right at k2.
Node structure
AVL node
struct avl { struct avl *left; /* pointers to the same structure type */ int info; int bf; /* balance factor (or store the height) */ struct avl *right;};
Key takeaways
AVL: heights of the two subtrees differ by at most 1 at every node.
bf =h(right)−h(left)∈{−1,0,+1}; ±2 triggers a rotation.
LL → right rotation; RR → left rotation; LR and RL → double rotations.
Height <1.44log2(n+2), so all operations are O(logn) worst case.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Insert 30, 10, 20 into an empty AVL tree, showing the balance factors and the rotation(s) used.
Show worked answer
Insert 30: bf(30) = 0. Insert 10 (left of 30): bf(30) = −1. Insert 20: 20 < 30, go left to 10; 20 > 10, so 20 is the right child of 10. Now bf(10) = +1 and bf(30) = −2: unbalanced at 30, path left then right: LR case. Double rotation: left rotation at 10 gives 30(20(10, -), -), then right rotation at 30 gives 20(10, 30). All balance factors are 0.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-208/advanced-trees/avl-trees-and-rotations/ to read this page.