A binary search tree finds keys in O(log n) only while it stays bushy. Insert sorted data and it degrades into a long chain, and every search becomes O(n). An AVL tree, named after its inventors Adelson-Velsky and Landis, fixes this automatically. After each insertion it checks that the heights of every node’s two subtrees differ by at most one, and if not, it repairs the shape with small local moves called rotations.
In this lesson you will learn
- Height and the balance factor
- Left and right rotations
- The four imbalance cases: LL, RR, LR and RL
- Inserting into an AVL tree in C
- How much shorter an AVL tree stays than a plain BST
You should already know the Binary Search Tree and recursion.
Insertion With Rotations
#include <stdio.h>
#include <stdlib.h>
struct Node { int key, height; struct Node *left, *right; };
static int height(const struct Node *n) { return n ? n->height : 0; }
static int max(int a, int b) { return a > b ? a : b; }
static void update(struct Node *n) { n->height = 1 + max(height(n->left), height(n->right)); }
static int balance(const struct Node *n) { return n ? height(n->left) - height(n->right) : 0; }
static struct Node *rotate_right(struct Node *y) {
struct Node *x = y->left;
y->left = x->right;
x->right = y;
update(y); update(x);
return x;
}
static struct Node *rotate_left(struct Node *x) {
struct Node *y = x->right;
x->right = y->left;
y->left = x;
update(x); update(y);
return y;
}
struct Node *insert(struct Node *node, int key) {
if (node == NULL) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->key = key; n->height = 1; n->left = n->right = NULL;
return n;
}
if (key < node->key) node->left = insert(node->left, key);
else if (key > node->key) node->right = insert(node->right, key);
else return node; /* no duplicates */
update(node);
int b = balance(node);
if (b > 1 && key < node->left->key) { /* Left-Left */
printf(" LL case at %d -> right rotation\n", node->key);
return rotate_right(node);
}
if (b < -1 && key > node->right->key) { /* Right-Right */
printf(" RR case at %d -> left rotation\n", node->key);
return rotate_left(node);
}
if (b > 1 && key > node->left->key) { /* Left-Right */
printf(" LR case at %d -> left then right rotation\n", node->key);
node->left = rotate_left(node->left);
return rotate_right(node);
}
if (b < -1 && key < node->right->key) { /* Right-Left */
printf(" RL case at %d -> right then left rotation\n", node->key);
node->right = rotate_right(node->right);
return rotate_left(node);
}
return node;
}
static void preorder(const struct Node *n) {
if (!n) return;
printf("%d(h%d) ", n->key, n->height);
preorder(n->left); preorder(n->right);
}
static void free_tree(struct Node *n) { if (n) { free_tree(n->left); free_tree(n->right); free(n); } }
int main(void) {
int keys[] = {10, 20, 30, 40, 50, 25};
struct Node *root = NULL;
for (int i = 0; i < 6; i++) {
printf("Insert %d\n", keys[i]);
root = insert(root, keys[i]);
}
printf("Preorder: ");
preorder(root);
printf("\nRoot = %d, tree height = %d\n", root->key, height(root));
free_tree(root);
return 0;
}
Output
Insert 10
Insert 20
Insert 30
RR case at 10 -> left rotation
Insert 40
Insert 50
RR case at 30 -> left rotation
Insert 25
RL case at 20 -> right then left rotation
Preorder: 30(h3) 20(h2) 10(h1) 25(h1) 40(h2) 50(h1)
Root = 30, tree height = 3
- Each node stores its height: 1 for a leaf, and 1 plus the taller child’s height otherwise.
updaterecalculates it after changes. - The balance factor is
height(left) - height(right). In an AVL tree it must be -1, 0 or 1 at every node. - Insertion is a normal recursive BST insert. On the way back up, each node updates its height and checks its balance.
- A right rotation lifts the left child up and moves the old root down to the right. A left rotation is the mirror. Both keep the BST ordering and take O(1) time.
- Inserting 10, 20, 30 makes a right-leaning chain (RR case), fixed by one left rotation at 10. Inserting 25 later creates a right-then-left zigzag (RL case), which needs two rotations.
- Six keys end in a tree of height 3, with 30 at the root, and every node is balanced.
The Four Cases
| Case | Shape | Fix |
|---|---|---|
| Left-Left (LL) | Inserted into the left child’s left subtree | One right rotation |
| Right-Right (RR) | Inserted into the right child’s right subtree | One left rotation |
| Left-Right (LR) | Inserted into the left child’s right subtree | Left rotate the child, then right rotate the node |
| Right-Left (RL) | Inserted into the right child’s left subtree | Right rotate the child, then left rotate the node |
Why Balance Matters
#include <stdio.h>
#include <stdlib.h>
/* Insert the sorted keys 1..n into a plain BST and an AVL tree, then compare heights */
struct Node { int key, h; struct Node *l, *r; };
static int H(const struct Node *n) { return n ? n->h : 0; }
static int mx(int a, int b) { return a > b ? a : b; }
static void up(struct Node *n) { n->h = 1 + mx(H(n->l), H(n->r)); }
static struct Node *mk(int k) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->key = k; n->h = 1; n->l = n->r = NULL;
return n;
}
/* Plain BST insert (iterative, so a long chain cannot overflow the stack) */
static struct Node *bst_insert(struct Node *root, int k) {
struct Node *node = mk(k);
if (!root) return node;
struct Node *p = root;
for (;;) {
struct Node **next = (k < p->key) ? &p->l : &p->r;
if (!*next) { *next = node; break; }
p = *next;
}
return root;
}
static int bst_height(const struct Node *n) {
if (!n) return 0;
int depth = 0; /* walk down: sorted input makes a chain */
while (n) { depth++; n = n->r ? n->r : n->l; }
return depth;
}
static struct Node *rot_r(struct Node *y) { struct Node *x = y->l; y->l = x->r; x->r = y; up(y); up(x); return x; }
static struct Node *rot_l(struct Node *x) { struct Node *y = x->r; x->r = y->l; y->l = x; up(x); up(y); return y; }
static struct Node *avl_insert(struct Node *n, int k) {
if (!n) return mk(k);
if (k < n->key) n->l = avl_insert(n->l, k); else n->r = avl_insert(n->r, k);
up(n);
int b = H(n->l) - H(n->r);
if (b > 1) { if (k > n->l->key) n->l = rot_l(n->l); return rot_r(n); }
if (b < -1) { if (k < n->r->key) n->r = rot_r(n->r); return rot_l(n); }
return n;
}
static void free_avl(struct Node *n) { if (n) { free_avl(n->l); free_avl(n->r); free(n); } }
static void free_chain(struct Node *n) { while (n) { struct Node *next = n->r; free(n); n = next; } }
int main(void) {
int sizes[] = {15, 1000, 5000};
printf("%8s %12s %12s\n", "n", "BST height", "AVL height");
for (int s = 0; s < 3; s++) {
struct Node *bst = NULL, *avl = NULL;
for (int i = 1; i <= sizes[s]; i++) {
bst = bst_insert(bst, i);
avl = avl_insert(avl, i);
}
printf("%8d %12d %12d\n", sizes[s], bst_height(bst), H(avl));
free_chain(bst);
free_avl(avl);
}
return 0;
}
Output
n BST height AVL height
15 15 4
1000 1000 10
5000 5000 13
- Inserting the keys 1 to n in order turns a plain BST into a chain of height n, so finding the largest key takes n steps.
- The AVL tree stays close to log2(n): height 13 for 5,000 keys. A search there visits at most 13 nodes instead of 5,000.
- The plain BST insert is written as a loop, because the recursive version would recurse 5,000 levels deep on a chain.
- An AVL tree’s height is always below about 1.44 × log2(n), which guarantees O(log n) search, insert and delete.
Common Mistakes
- Forgetting to update heights after a rotation, or updating the parent before the child.
- Not returning the new subtree root from a rotation, which detaches part of the tree.
- Mixing up LR and RL; check the direction from the unbalanced node to the new key.
- Treating a missing child’s height as 1; a
NULLsubtree has height 0.
Practice Exercises
Exercise 1. Which rotations happen when inserting 30, 20, 10 into an empty AVL tree?
Show answer
After 10, node 30 has balance +2 and 10 went left of its left child: the LL case. One right rotation at 30 makes 20 the root with children 10 and 30.
Exercise 2. Write is_balanced that checks the AVL property of every node.
Show answer
int is_balanced(const struct Node *n) {
if (!n) return 1;
int b = height(n->left) - height(n->right);
return b >= -1 && b <= 1 && is_balanced(n->left) && is_balanced(n->right);
}
Frequently Asked Questions
What is the difference between AVL and red-black trees?
AVL trees are more strictly balanced, so lookups are slightly faster. Red-black trees allow a little more imbalance and need fewer rotations on insert and delete, which is why many standard libraries use them for maps and sets.
How does deletion work in an AVL tree?
Delete as in a normal BST, then walk back up updating heights and applying the same four rotation cases wherever the balance factor reaches 2 or -2. Deletion can require rotations at several levels.
Summary
- An AVL tree keeps every balance factor in {-1, 0, 1}.
- Rotations restore balance in O(1) while keeping BST order.
- Four cases: LL, RR (single rotation), LR, RL (double rotation).
- Height stays O(log n), so operations stay O(log n) even for sorted input.
Next: Trie Data Structure in C.
