What is a self-balancing tree

A self-balancing binary search tree is a BST that reshapes itself after every insert and delete so its height stays proportional to log n. The ordering rule is the same as in a plain BST; the new part is a limit on height.

The tree enforces that limit with one local operation, a rotation, applied a handful of times per write. A rotation changes at most three pointers, and this article is about how it works and when to apply it.

The bookshelf analogy

Imagine a shelf where you always add new books to the right end. Reach for a book and you walk the shelf from the left. That's fine at first and tedious once the shelf is long.

Now imagine the shelf reorganises itself: whenever one side grows taller than the other, it picks one book as the new middle and hangs the two halves off it. Only that book changes position, and the whole shelf gets shallower. That move is a rotation.

The problem a Binary Search Tree couldn't solve

The previous article ended on a structure with excellent average behaviour and no floor under its worst case. Insert values in ascending order and every one goes right, producing a tree of height n − 1: a linked list with an unused pointer per node.

Worse, the bad case is the ordinary one. Data comes from an ORDER BY, from an auto-incrementing id, from a timestamp, from a sorted file. You can't put a structure that collapses on the most common input shape behind a production query.

The goal, then, is to keep every guarantee the BST already offers (ordered iteration, range queries, O(h) operations) while making h provably O(log n) no matter what order the data arrives in.

Rotations

A rotation takes a parent and one of its children and swaps which of them is on top, then reattaches the subtrees so the ordering rule still holds.

A right rotation

The left child rises, the parent sinks to become its right child.

Before: 30 leans left, and the tree is height 2
+230+120010

balance factor of 30 is +2, which is one past the limit

After a right rotation: 20 rises, and the tree is height 1
020010030

the same three values, one level shorter

Three pointer writes, and the height dropped. Deciding to reshape took no comparison of values, only the observation that one side was too tall.

A left rotation is the exact mirror: the right child rises and the parent becomes its left child. Everything below applies to both, with left and right swapped, which is why implementations write one and derive the other.

Why the invariant survives

A rotation is only legal if the ordering rule still holds afterward, so it's worth checking that it does. The interesting part is a subtree hanging off the child that rises, because that subtree has to move. Watch where it lands:

Before: 25 is 20's right child
3020401025

25 sits between 20 and 30, which is what makes the next step legal

After: 25 is now 30's left child
2010302540

the same five values in the same order, only rearranged

The value 25 was in 20's right subtree, so by the invariant it is greater than 20. And it was in 30's left subtree, so it is less than 30. Those are exactly the two conditions for being a legal member of 30's left subtree after the rotation, so nothing inside the subtree needs checking.

The same argument works for every rotation. A rotation only ever moves the middle subtree, and the middle subtree is by definition bounded by the two nodes swapping places, so it is legal on both sides of the operation. Reading the values left to right gives the same sequence before and after, which shows directly that nothing was broken.

AVL trees

An AVL tree, named for Adelson-Velsky and Landis (1962), was the first self-balancing BST. It enforces the strictest useful condition: for every node, its two subtrees differ in height by at most one.

The balance factor

Each node carries, or can compute, a balance factor: the height of its left subtree minus the height of its right. Legal values are -1, 0 and +1. Anything else means that node needs work.

Balance factors, all within limits
+150+130070020

50 and 30 each lean left by one, which is legal, so no rotation

After an insert, only the nodes on the path from the new leaf back to the root can have changed height, so only those need checking. That is O(log n) nodes with an O(1) fix at each, so the whole insert stays logarithmic.

The four cases

When a node's factor reaches ±2, which way to rotate depends on where the excess height actually is. There are four configurations: two shapes plus their mirrors.

Left-left. The node leans left, and its left child also leans left. One right rotation fixes it; this is the figure from earlier in the article.

Left-left: the lean is on the outside
+230+120010

30 leans left, 20 leans left · one right rotation

Left-right. The node leans left, but its left child leans right. A single right rotation here doesn't help, because it just moves the problem to the other side. First rotate the child left, which turns this into the left-left case, then rotate the node right.

Left-right: the lean is on the inside
+230−110020

30 leans left, 10 leans right · rotate 10 left first, then 30 right

Right-right. The mirror of left-left: the node leans right, and its right child also leans right. One left rotation fixes it.

Right-right: the lean is on the outside
−210−120030

10 leans right, 20 leans right · one left rotation

Right-left. The mirror of left-right: the node leans right, but its right child leans left. Rotate the child right first, which turns this into the right-right case, then rotate the node left.

Right-left: the lean is on the inside
−210+130020

10 leans right, 30 leans left · rotate 30 right first, then 10 left

So the whole decision table is: look at the node's lean, look at its child's lean, and if they disagree do an extra rotation first to make them agree.

Deletion

Delete works the same way: perform the BST delete from the previous article, then walk back up rebalancing. The difference is in the number of rotations. An insert needs at most one rotation to restore the whole tree, while a delete can need one at every level on the way up, so O(log n) of them.

Red-black trees

The ordered maps in the usual standard libraries aren't AVL trees. std::map, TreeMap, and the Linux kernel's scheduler all use red-black trees, which enforce a looser condition through a different mechanism: every node is painted red or black, and the colours obey rules that bound the height indirectly.

The five rules

  1. Every node is red or black.
  2. The root is black.
  3. All leaves (the null children) count as black.
  4. A red node's children are both black, so two reds never appear in a row.
  5. Every path from a node down to any of its null descendants passes through the same number of black nodes.
A red-black tree, with R and B marking the colours
B13R8R17B1B11B15B25

no red node has a red child, and every root-to-null path crosses two blacks

Most of the balancing comes from rule 5: if you count only black nodes, the tree is perfectly balanced. Rule 4 then caps how many reds can pad a path (at most one red between blacks), so the longest path is at most twice the shortest. Height is bounded by 2 · log₂(n+1), which is O(log n) with a worse constant than AVL.

Why the libraries chose red-black

AVL trees are shorter, so their lookups are marginally faster. Red-black trees won anyway because of the delete asymmetry from the AVL section.

Red-black repairs use recolouring first and only rotate when recolouring is not enough. Flipping a colour moves no pointers, so it's free, and many insertions and deletions resolve with no structural change at all. A red-black delete needs at most three rotations, ever; an AVL delete can need O(log n).

So the trade is: AVL is faster to read, red-black is faster to write and has a tighter bound on the work a single operation can do. For a general-purpose container in a standard library, where writes are common and predictable latency matters, that is the better default.

Try it yourself

The same playground as the previous article, with balancing switched on. Press Insert in ascending order, the input that produced height 6 last time, and watch it stay logarithmic. The status line names the rotation each time one fires, and every node shows its balance factor.

Your AVL tree7 nodes · h 2, balanced
02003004005006007008045

type a value to see where it would land · click a node to delete it

read left to right
20304050607080
100%
Operation log
  1. every step of the next run shows up here
0/0

insert, search or delete — the path lights up as it walks

Also try inserting values one at a time and watch the balance factors climb toward ±2 until a rotation resets them.

Common operations and their costs

The previous article's table needed a "degenerate" column showing O(n). This one has no such column, because there is no bad case to show.

OperationAVLRed-black
Search
Insert
Delete
Rotations per write
Height bound

Every cell is O(log n). The differences are constant factors that point in opposite directions, which is why both structures are still in use.

Balanced trees in the real world

Ordered containers in standard libraries. std::map and std::set in C++, TreeMap and TreeSet in Java, BTreeMap in Rust. When a language offers a sorted map alongside a hash map, the sorted one is a balanced tree, and usually red-black.

The Linux kernel. The completely fair scheduler keeps runnable tasks in a red-black tree keyed by how much CPU time they have had, so "who runs next" is the leftmost node. epoll uses one to track watched file descriptors, and the virtual memory system uses one for address ranges. The reason is the predictable worst case: a scheduler cannot afford an occasional O(n).

Database indexes, and where B-trees come in. The CREATE INDEX in your migration almost certainly builds a B-tree. It's the same idea with a different constant: instead of one value and two children per node, a B-tree node holds hundreds of values and hundreds of children, sized so one node fills one disk page.

The cost model is different. In memory you pay for comparisons; on disk you pay for page reads, and a page read costs the same whether you use one value from it or five hundred. Enormous nodes make the tree shallow (a few levels cover millions of rows), so a lookup is a handful of page reads instead of twenty.

This is what the hash tables article was pointing at when it noted that PostgreSQL defaults to B-tree indexes and offers hash indexes only as a specialisation. The B-tree default buys you ORDER BY without a sort and BETWEEN without a scan, both from the ordering property, and a hash index can offer neither.

When balanced trees fall short

You pay on every write. Maintaining the invariant is work that a plain BST does not do. If your workload is write-heavy and lookups are rare, or if you know your insertion order is already random, the rebalancing is overhead buying a guarantee you were not going to need.

A hash table is still faster for exact lookups. Average O(1) beats guaranteed O(log n), and the gap is wider than the notation suggests. Balancing does not change the decision from the previous article: choose a tree for ordering, a hash table for pure key-value access.

Still pointer chasing. A balanced tree guarantees you touch only log n nodes, but those nodes can sit anywhere in memory. Twenty guaranteed cache misses beat a million and still lose to the sequential read an array gives you. The same problem is why the disk-oriented case moved to B-trees instead of balanced binary trees.

Bulk-loading sorted data deserves better. If you already have n sorted values, inserting them one at a time costs O(n log n) and a pile of rotations, when you could build a perfectly balanced tree directly in O(n) by taking the middle value as the root and recursing. Libraries expose this as a range constructor; use it when you have it.

Correctness is hard. Delete is where hand-written balanced trees break, and the failures are silent: the tree stays a valid BST while losing its height guarantee, so it keeps working and slowly gets slower.

Summary

Balanced trees keep everything a BST offers and add a floor under the worst case:

  • A rotation swaps a parent with a child: three pointer writes, and it can only move the middle subtree, which the invariant already proved legal on both sides
  • In-order sequence is preserved exactly, so sorted iteration, range queries, minimum and maximum all survive; only the shape changes
  • AVL keeps every balance factor within one: four rotation cases, which are two shapes and their mirrors, and the double cases exist only to turn an inside lean into an outside one
  • Red-black bounds height with colours: no two reds in a row and equal black counts on every path, giving 2 log n
  • Libraries chose red-black: recolouring is free, so writes rarely rotate, and a delete needs at most three rotations against AVL's O(log n)
  • B-trees are the same idea for disk: hundreds of values per node, because the unit of cost is a page read, not a comparison

Balancing turns an average-case guarantee into a worst-case one and pays a constant factor on writes to do it. A plain BST is already O(log n) on random input and breaks on the input you are most likely to have, data that arrives in order. A few rotations per write are enough to prevent that.