Balanced trees: AVL and red-black
A balanced tree reshapes itself after inserts so its height stays O(log n): an AVL tree rotates when its two sides differ in height by more than 1, std::set and std::map are red-black trees, and databases use B+ trees.
In chapter 4's binary search tree lesson, 300 values inserted in order made the tree 300 tall, and searching fell back to O(n). The binary search tree itself isn't the problem; it's that it doesn't care what shape it grows into. A balanced tree checks its shape after every insert and delete, and when it leans, fixes it, so the height stays O(log n).
AVL trees: left and right differ by at most 1
The AVL tree (named after its two inventors) was the first balanced tree. On top of the binary search tree's rule it adds one more: at every node, the left and right subtrees' heights may differ (the balance factor) only by −1, 0 or 1. After inserting a value, go up from it; the first node whose balance factor has become ±2 is where it's unbalanced, and one rotation there fixes it.
Balance factors are recomputed one by one from the new node upward. Here it is with 10, 20, 30 inserted in that order:
Insert 5, 3, 8, 1 in that order into an empty AVL tree (no rotation needed). What is the balance factor of the root, 5?
Is it balanced?
✓Decide whether every node of a binary tree has left and right heights differing by at most 1. The trick: check returns the height, and returns -1 as soon as it finds an imbalance, passing it all the way up.
1 0
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), left(l), right(r) {}9};10 11int check(Node* t) {12 // empty tree: 0; left or right is -1: -1; heights differ by > 1: -1; otherwise return the height13 return 0;14}15 16int main() {17 Node* a = new Node(1, new Node(2, new Node(4)), new Node(3));18 Node* b = new Node(1, new Node(2, new Node(4, new Node(5))), new Node(3));19 cout << (check(a) != -1) << " " << (check(b) != -1) << endl;20 return 0;21}
Four kinds of imbalance, two rotations
After an insertion, walk up from the new node: the first node whose balance factor becomes ±2 is the one to fix. There are only two moves to fix it with: rotating right and rotating left.
There are four kinds, named by "which side of which child of the unbalanced node the new node went into":
| Imbalance | The new node went into | The fix |
|---|---|---|
| LL | the left child's left subtree | rotate right once |
| RR | the right child's right subtree | rotate left once |
| LR | the left child's right subtree | rotate the left child left, then this node right |
| RL | the right child's left subtree | rotate the right child right, then this node left |
Rotating right: the left child comes up as the root, the old root becomes its right child, and the left child's old right subtree hangs on the old root's left. Rotating left is the mirror image.
Insert 30, 10, 20 in that order into an empty AVL tree. Which kind of imbalance is it, and what is the root after the fix?
Put the 6 lines of the left rotation rot_left in order: the right child r comes up and t becomes r's left child.
fix(t);r->left = t;Node* r = t->right;return r;fix(r);t->right = r->left;
2 1 3 2
Rotate right
✓Finish rot_right: the left child l comes up, t becomes l's right child, l's old right subtree hangs on t's left; update t's height first, then l's.
5 3 1 8 6 9 height 3
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), h(1), left(l), right(r) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* make(int v, Node* l = nullptr, Node* r = nullptr) {15 Node* n = new Node(v, l, r);16 fix(n);17 return n;18}19 20Node* rot_right(Node* t) {21 // l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l22 return t;23}24 25void pre(Node* t) {26 if (!t) return;27 cout << t->val << ' ';28 pre(t->left);29 pre(t->right);30}31 32int main() {33 // 8's left 5(3(1, _), 6) is 2 taller than its right 9: LL34 Node* t = make(8, make(5, make(3, make(1)), make(6)), make(9));35 t = rot_right(t);36 pre(t);37 cout << "\nheight " << t->h << endl;38 return 0;39}
In C++: check after every insertion
Each node stores one more field, h: how tall the subtree rooted at it is. A rotation changes just three pointers; afterwards update the height of the node that ended up lower first, then the one above it.
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h; // h: the height of the subtree it's the root of7 Node *left, *right;8 Node(int v) : val(v), h(1), left(nullptr), right(nullptr) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { // the left child comes up15 Node* l = t->left;16 t->left = l->right;17 l->right = t;18 fix(t);19 fix(l);20 return l;21}22 23Node* rot_left(Node* t) { // the right child comes up24 Node* r = t->right;25 t->right = r->left;26 r->left = t;27 fix(t);28 fix(r);29 return r;30}31 32Node* insert(Node* t, int v) {33 if (!t) return new Node(v);34 if (v < t->val) t->left = insert(t->left, v);35 else t->right = insert(t->right, v);36 fix(t);37 int bf = H(t->left) - H(t->right); // the balance factor38 if (bf > 1 && v < t->left->val) return rot_right(t); // LL39 if (bf < -1 && v > t->right->val) return rot_left(t); // RR40 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); } // LR41 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); } // RL42 return t;43}44 45void destroy(Node* t) { // postorder: the children first, then itself46 if (!t) return;47 destroy(t->left);48 destroy(t->right);49 delete t;50}51 52int main() {53 Node* t = nullptr;54 for (int i = 1; i <= 1000; i++)55 t = insert(t, i); // in order: a plain binary search tree would be 1000 tall56 cout << "AVL tree: 1000 values, height " << t->h << ", root " << t->val << endl;57 destroy(t);58 return 0;59}
AVL tree: 1000 values, height 10, root 512
With 1000 values inserted in order, the AVL tree is only 10 tall, about log₂ 1000. Each insert turns at most twice, and search, insert and delete are all O(log n). The nodes made with new are freed at the end by destroy, in postorder; the guesses and exercises in this lesson leave that step out to stay short.
Insert 1 to 7 into an AVL tree in order. What does preorder print?
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v) : val(v), h(1), left(nullptr), right(nullptr) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { Node* l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }15Node* rot_left(Node* t) { Node* r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }16 17Node* insert(Node* t, int v) {18 if (!t) return new Node(v);19 if (v < t->val) t->left = insert(t->left, v);20 else t->right = insert(t->right, v);21 fix(t);22 int bf = H(t->left) - H(t->right);23 if (bf > 1 && v < t->left->val) return rot_right(t);24 if (bf < -1 && v > t->right->val) return rot_left(t);25 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }26 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }27 return t;28}29 30void pre(Node* t) {31 if (!t) return;32 cout << t->val << ' ';33 pre(t->left);34 pre(t->right);35}36 37int main() {38 Node* t = nullptr;39 for (int i = 1; i <= 7; i++) t = insert(t, i);40 pre(t);41 cout << endl;42 return 0;43}
Which rotation does the LL case (the new node to the left of the left child) call? Fill in the blank so the tree built from 7 down to 1 stays balanced.
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), h(1), left(l), right(r) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { Node* l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }15Node* rot_left(Node* t) { Node* r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }16 17Node* insert(Node* t, int v) {18 if (!t) return new Node(v);19 if (v < t->val) t->left = insert(t->left, v);20 else t->right = insert(t->right, v);21 fix(t);22 int bf = H(t->left) - H(t->right);23 if (bf > 1 && v < t->left->val) return (t);24 if (bf < -1 && v > t->right->val) return rot_left(t);25 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }26 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }27 return t;28}29 30void pre(Node* t) {31 if (!t) return;32 cout << t->val << ' ';33 pre(t->left);34 pre(t->right);35}36 37int main() {38 Node* t = nullptr;39 for (int i = 7; i >= 1; i--) t = insert(t, i);40 pre(t);41 cout << endl;42 return 0;43}
rot_right. With rot_left, it reaches for a right child that isn't there and the program stops.B-trees: many keys in one node
When there's too much data for memory and it lives on disk, things change: one read from disk takes milliseconds, a hundred thousand times slower than memory, and it always reads a whole block (a few KB). What matters most is how many times the disk is read, which is the tree's height.
A B-tree gives each node many keys and many children: one node is exactly one disk block, its keys sorted, and the child between two keys holds the values between those two keys.
With 1000 keys a node, three levels hold a billion keys (1000 × 1000 × 1000), and any of them is found in 3 disk reads. A B-tree also keeps all its leaves on the same level: when a node is full on insert it splits in two and moves the middle key up into its parent, so it's always balanced.
In the B-tree of order 3 at the start of this stage, how many disk reads does it take to find 61?
B+ trees, and which tree to use
A database doesn't just need to "find one", it often needs to "find a range". The B+ tree is the B-tree reworked for that.
A B+ tree is a variant: all the data sits in the leaves, the inner nodes hold only keys for finding the way, and the leaves are linked in a list. A range query ("scores from 60 to 80") then finds the start and reads along the list. MySQL's InnoDB storage engine and most file systems' indexes are B+ trees.
| Structure | Each node | Suits | Used in |
|---|---|---|---|
| AVL tree | 1 key, 2 children | memory, many lookups | textbooks, exams |
| Red-black tree | 1 key, 2 children | memory, many inserts and deletes too | std::set, std::map, Java TreeMap |
| B-tree / B+ tree | many keys and children | disk, where a read is a whole block | database indexes, file systems |
In exams: AVL questions give an insert sequence and ask, at each step, whether it's unbalanced, which kind, and what the tree looks like after the turn; or "the fewest nodes in an AVL tree of height h" (N(h) = N(h − 1) + N(h − 2) + 1, N(1) = 1, N(2) = 2). B-trees are usually asked only as ideas: in a B-tree of order m, each node has at most m children, and every node but the root at least ⌈m / 2⌉; all leaves are on one level.
In a B-tree of order 5, how many children must every node except the root have, at least?
You need the records with a score between 60 and 80 out of several million. Which structure fits best?
With the STL
In C++ you don't write a balanced tree yourself: std::set and std::map (and multiset, multimap) are all red-black trees inside. A red-black tree colours every node red or black and keeps four rules:
- The root is black.
- A red node's children are both black (no two reds in a row).
- From any node down to an empty spot, every path has the same number of black nodes.
- Empty spots (
nullptr) count as black.
From 2 and 3, the longest path (alternating red and black) is at most twice the shortest (all black), so the height is at most 2 log₂(n + 1). It's not as even as an AVL tree, but it turns less on inserts and deletes (at most two rotations per insert, three per delete), and most of the time it just recolours. That's what a standard library wants: with plenty of inserts, deletes and lookups, it's faster overall.
Insert 1, 2, …, 1000 in order again, give the set a comparison that counts, and see how many comparisons looking up each value takes:
1#include <iostream>2#include <set>3using namespace std;4 5long cmps = 0;6 7struct CountLess { // just like <, but counts every comparison8 bool operator()(int a, int b) const {9 cmps++;10 return a < b;11 }12};13 14int main() {15 set<int, CountLess> s;16 for (int i = 1; i <= 1000; i++) s.insert(i); // in order: a plain BST would become a chain17 cout << "inserting 1000 values: " << cmps << " comparisons in all" << endl;18 19 long worst = 0, total = 0;20 for (int i = 1; i <= 1000; i++) {21 cmps = 0;22 s.find(i);23 total += cmps;24 if (cmps > worst) worst = cmps;25 }26 cout << "lookups: " << total / 1000.0 << " on average, at most " << worst << endl;27 return 0;28}
inserting 1000 values: 16479 comparisons in all lookups: 11.389 on average, at most 18
An insert takes a little over 16 comparisons on average; a lookup a little over 11 on average and at most 18 (find first walks to the bottom for "the first not less than x", then compares once more), never above the red-black limit of 2 log₂ 1000 ≈ 20. The plain binary search tree, fed values in order, takes 1000 comparisons to find the last one.
With balance, set / map are containers that are "always sorted and quick to change". Say a timetable sorted by time, with things added and removed at any moment, and the question "what's next after a given time":
1#include <iostream>2#include <map>3#include <string>4using namespace std;5 6int main() {7 map<int, string> plan; // minutes since midnight -> event, sorted8 plan[540] = "class";9 plan[720] = "lunch";10 plan[600] = "meeting";11 plan[900] = "run";12 plan.erase(600); // the meeting is cancelled: O(log n)13 plan[840] = "office hours";14 15 for (auto& kv : plan) // iterating: smallest first16 cout << kv.first / 60 << ":" << (kv.first % 60 < 10 ? "0" : "") << kv.first % 6017 << " " << kv.second << endl;18 19 auto it = plan.lower_bound(750); // the next event after 12:3020 cout << "after 12:30: " << it->second << endl;21 if (it != plan.begin()) {22 --it; // back one: the latest before 12:3023 cout << "before 12:30: " << it->second << endl;24 }25 cout << "earliest " << plan.begin()->second << ", latest " << plan.rbegin()->second << endl;26 return 0;27}
9:00 class 12:00 lunch 14:00 office hours 15:00 run after 12:30: office hours before 12:30: lunch earliest class, latest run
lower_bound is map's own member function: one path down from the root, O(log n). Once you have the iterator, --it and ++it are the previous and next in inorder.
| Operation | set / map (red-black tree) | sorted vector | plain BST (worst) |
|---|---|---|---|
lookup find, count | O(log n) | O(log n) (binary search) | O(n) |
| insert, delete | O(log n) | O(n): it moves things | O(n) |
lower_bound(x) | O(log n), the member function | O(log n) | O(n) |
| iterate in order | O(n) | O(n) | O(n) |
| smallest, largest | O(1): begin(), rbegin() | O(1) | O(n) |
Press Visualize on this program and step through: s is drawn as the red-black tree inside it, red and black nodes, recoloured and rotated after each insert exactly as in g++:
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s;7 int a[] = {40, 20, 60, 10, 30, 50, 70, 25};8 for (int x : a) s.insert(x);9 cout << s.size() << " " << *s.begin() << " " << *s.rbegin() << "\n";10 return 0;11}
8 10 70
In interviews: "what's under std::map?" Say a red-black tree, and why not AVL: lookups are about as fast, and inserts and deletes rotate less. Writing a red-black tree by hand is almost never asked (insertion has too many cases); being able to state the rules and knowing the height is ≤ 2 log₂(n + 1) is enough. Whether you need order is what decides between map and unordered_map: no order, lookups by "equal" only, and the hash table's average O(1) is faster.
What makes a red-black tree better than an AVL tree?
After these inserts and an erase, what does the set print?
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s = {40, 20, 60, 10, 30};7 s.insert(20);8 s.erase(60);9 auto it = s.lower_bound(25);10 cout << s.size() << " " << *it << " " << *s.rbegin() << endl;11 return 0;12}
set keeps no duplicates, so inserting 20 again changes nothing; after erasing 60, 10 20 30 40 are left: 4 of them. lower_bound(25) is the first element not less than 25: 30. rbegin() points at the largest: 40.Summary
Balanced trees: turn when it leans, keep the height O(log n)
- AVL: left and right heights differ by ≤ 1 at every node; after an insert find the first unbalanced node
- LL rotate right, RR rotate left, LR left then right, RL right then left
- Red-black: no two reds in a row, the same number of blacks on every path, height ≤ 2 log₂(n + 1)
- set / map are red-black trees: insert, erase, find, lower_bound all O(log n), iteration in order
- B-trees / B+ trees: many keys a node, a short tree, few disk reads; database indexes
1Node* rot_right(Node* t) {2 Node* l = t->left;3 t->left = l->right; l->right = t;4 fix(t); fix(l);5 return l;6}