AVL Tree
Insert
–
Pseudocode
1insert v like in a normal binary search tree2walk back up from the new node towards the root:3 update height; balance ← height(left) − height(right)4 balance > 1 and balance(left) ≥ 0: rotate right // LL5 balance > 1 and balance(left) < 0: rotate left at left, then right // LR6 balance < −1 and balance(right) ≤ 0: rotate left // RR7 balance < −1 and balance(right) > 0: rotate right at right, then left // RL
Comparisons
0
Rotations
0
Height
0
+1balance factor (red when ±2)node being checkedinserted / found
What is an AVL Tree?
An AVL tree (Adelson-Velsky and Landis, 1962) is a binary search tree that never gets lopsided. Every node keeps its balance factor, the height of its left subtree minus the height of its right subtree, at −1, 0 or +1.
A plain BST built from sorted input turns into a long chain, so searches become O(n). An AVL tree checks the balance factors on the way back up after every insert or delete. When one reaches ±2, it fixes it with one or two rotations, so the height and every operation stay O(log n).
After every change, walk back up; any node with balance ±2 gets rotated back into shape.
Using the Visualizer
- • Numbers beside the nodes are balance factors; they turn red at ±2, right before a rotation.
- • Press Insert in order to add 10, 20, …, 80: a plain BST would become a chain, AVL rotates instead.
- • Tags like LL, LR, RR, RL show which case is being fixed.
- • Delete a value to see rebalancing on the way up after removal too.
How It Works
LL: rotate right
Node too tall on the left, and its left child is not leaning right: one right rotation.
RR: rotate left
The mirror image: too tall on the right, right child not leaning left.
LR: left, then right
Left child leans right: rotate it left first (making it LL), then rotate right.
RL: right, then left
Right child leans left: rotate it right first (making it RR), then rotate left.
Rotations keep the order: a rotation lifts a child above its parent but never changes the in-order (sorted) sequence, so the tree is still a valid BST afterwards.
Implementation
Properties & Complexity
Time Complexity
- • Search, insert, delete: O(log n) worst case
- • Rotations per insert: at most 2
- • Rotations per delete: up to O(log n)
Space & Properties
- • Space: O(n), one height per node
- • Stricter balance than red-black trees: faster lookups, more rotations
Where It Is Used
- • Lookup-heavy sets and maps
- • Databases and indexes held in memory
- • Teaching: the classic example of a self-balancing tree
Limitations
- • More rotations than red-black trees on frequent inserts/deletes
- • Extra field: every node stores its height
- • Disk storage: B-trees are better when nodes live on disk