Balanced Trees
Why binary search trees need balancing, how AVL rotations work, how red-black trees and B-trees differ, and what interviewers ask about them.
On this page
A balanced tree is a binary search tree that rearranges itself after every insert and delete so that its height stays proportional to log n. It exists because an ordinary binary search tree can degrade into a linked list, which makes search, insert and delete O(n). You use a balanced tree when you need data kept in sorted order with fast lookup, insertion and deletion, and in practice you use the one your language's library provides.
The degradation happens when keys arrive in sorted order. If user IDs are inserted as 1, 2, 3 and so on, each new key becomes the right child of the previous one, and after a million inserts the tree is a single chain a million levels deep. A balanced tree makes the insert order irrelevant.
Why the height of the tree decides the speed
Search, insert and delete each follow one path from the root, so they cost O(h), where h is the height of the tree. A tree with a million nodes can be about 20 levels tall at best, and a chain of the same nodes is a million levels tall. A balanced tree does not have to reach the minimum height. It only has to keep the height within a constant factor of log₂ n, and that is enough to make every operation O(log n) in the worst case.
How an AVL tree keeps its balance
The AVL tree is the oldest balanced search tree, and it is the one usually taught because its rule is easy to state.
Each node stores the height of its subtree (see Binary Trees). The height of the left subtree minus the height of the right subtree is the node's balance factor, and it must be −1, 0 or +1. This rule keeps the height below about 1.44 log₂ n.
An insert works like an insert in a normal search tree, and then each node on the path back up to the root updates its height and checks its balance factor. If a node's balance factor has become 2 or −2, the node is repaired with one or two rotations.
Rotations
A rotation changes a few links so that one node moves up and another moves down, without breaking the search order. In a right rotation, node x's left child y becomes the top of the subtree, and x becomes the right child of y. A left rotation is the mirror image.
Only the subtree B changes its parent, from y to x. This is safe because every key in B is larger than y and smaller than x, so it fits in either place. Only three links change, so a rotation takes O(1) time.
Which rotation to use depends on the path from the unbalanced node toward the newly inserted key. If the path goes in a straight line (left then left, or right then right), one rotation at the unbalanced node is enough. If the path bends (left then right, or right then left), a single rotation would only move the bend to the other side, so you first rotate the child to straighten the path and then rotate the node. This two-step repair is called a double rotation.
A traced example with both kinds of rotation
The trace inserts 10, 20, 30, 25 and 28. The insert of 30 needs a single rotation, and the insert of 28 needs a double rotation.
insert like a normal BSTwalk back up; at each node: update its height if one side is 2 taller: if the path bends: rotate the child first rotate the node toward the shorter side- node
- 10
- left h
- 0
- right h
- 1
1After inserting 10 and then 20, node 10 has left height 0 and right height 1. A difference of 1 is allowed, so nothing changes.
- node
- 10
- left h
- 0
- right h
- 2
2Inserting 30 goes right and then right again. Node 10 now has left height 0 and right height 2, so it is off by 2 and must be fixed.
- node
- 20
- left h
- 1
- right h
- 1
3The path from 10 goes right and then right, which is a straight line. One left rotation at 10 lifts 20 to the top, and the height drops from 3 to 2.
- node
- 20
- left h
- 1
- right h
- 2
4Inserting 25 makes it the left child of 30. Node 30 leans left by 1 and the root leans right by 1, and both are allowed.
- node
- 30
- left h
- 2
- right h
- 0
5Inserting 28 goes right of 20, left of 30 and right of 25. On the way back up, node 30 has left height 2 and right height 0, so it is off by 2.
- node
- 30
- left h
- 2
- right h
- 0
6The path from 30 goes left and then right, so it bends. A right rotation at 30 alone would leave the bend in place, so the first step is a left rotation at 25 that makes 28 its parent.
- node
- 28
- left h
- 1
- right h
- 1
7The path 30, 28, 25 is now a straight line. A right rotation at 30 moves 28 to the top, with 25 and 30 as its children.
- height
- 3
- plain BST height
- 5
- rotations
- 3
8The tree is balanced again, and an inorder walk still reads 10, 20, 25, 28, 30. A plain search tree would have height 5 for these inserts, and this one has height 3 after 3 rotations.
AVL insert and rotations in code
The first block shows the two rotations and the height bookkeeping. The second block adds the function that repairs a node and the insert that calls it. Both functions return the new top of the subtree, so the parent can reattach it. Here an empty tree has height 0 and a single node has height 1.
// Each node has val, left, right and height.
function height(node) {
return node === null ? 0 : node.height;
}
function update(node) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
// x's left child y moves up, and x becomes y's right child.
function rotateRight(x) {
const y = x.left;
x.left = y.right; // the middle subtree B changes parent
y.right = x;
update(x); // x is lower now, so update it first
update(y);
return y; // the new top of this subtree
}
// The mirror image: x's right child y moves up.
function rotateLeft(x) {
const y = x.right;
x.right = y.left;
y.left = x;
update(x);
update(y);
return y;
}# Each node has val, left, right and height.
def height(node):
return 0 if node is None else node.height
def update(node):
node.height = 1 + max(height(node.left), height(node.right))
# x's left child y moves up, and x becomes y's right child.
def rotate_right(x):
y = x.left
x.left = y.right # the middle subtree B changes parent
y.right = x
update(x) # x is lower now, so update it first
update(y)
return y # the new top of this subtree
# The mirror image: x's right child y moves up.
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x)
update(y)
return yfunction balanceFactor(node) {
return height(node.left) - height(node.right);
}
function rebalance(node) {
update(node);
const bf = balanceFactor(node);
if (bf > 1) { // left side too tall
if (balanceFactor(node.left) < 0) { // the path bends
node.left = rotateLeft(node.left);
}
return rotateRight(node);
}
if (bf < -1) { // right side too tall
if (balanceFactor(node.right) > 0) { // the path bends
node.right = rotateRight(node.right);
}
return rotateLeft(node);
}
return node;
}
function insert(node, val) {
if (node === null) return { val, left: null, right: null, height: 1 };
if (val < node.val) node.left = insert(node.left, val);
else if (val > node.val) node.right = insert(node.right, val);
return rebalance(node);
}def balance_factor(node):
return height(node.left) - height(node.right)
def rebalance(node):
update(node)
bf = balance_factor(node)
if bf > 1: # left side too tall
if balance_factor(node.left) < 0: # the path bends
node.left = rotate_left(node.left)
return rotate_right(node)
if bf < -1: # right side too tall
if balance_factor(node.right) > 0: # the path bends
node.right = rotate_right(node.right)
return rotate_left(node)
return node
def insert(node, val):
if node is None:
return Node(val) # a node with height 1 and no children
if val < node.val:
node.left = insert(node.left, val)
elif val > node.val:
node.right = insert(node.right, val)
return rebalance(node)A delete calls rebalance on every node along the path back up in the same way. An insert needs at most one repair, while a delete can need one at every level.
Time and space cost
| Approach | Time | Space | Why |
|---|---|---|---|
| Plain search tree | O(n) worst case | O(n) | The height depends on the insert order and can reach n. |
| AVL tree | O(log n) | O(n) | The height stays below about 1.44 log₂ n, and each rotation is O(1). |
Variants of balanced trees
Red-black trees
A red-black tree colours every node red or black and enforces three rules. The root is black, a red node never has a red child, and every path from a node down to an empty position passes the same number of black nodes. Together these rules guarantee that the longest path is at most twice as long as the shortest, so the height stays below about 2 log₂ n.
Compared with an AVL tree, a red-black tree is allowed to be less tidy. Lookups can take a few more steps, but updates are cheaper, because most repairs only recolour nodes and an insert needs at most two rotations. For this reason most standard libraries use red-black trees. Java's TreeMap and C++'s std::map (in common implementations) are red-black trees. You should be able to state the three rules, but interviews rarely ask you to code them.
B-trees
A B-tree is built for data stored on disk. Following a pointer in memory is cheap, but each node visited on disk can mean a separate read that is thousands of times slower, so the goal is to visit as few nodes as possible. A B-tree node holds many sorted keys, often hundreds, and has one more child than it has keys. The keys split the range of values the same way a single key splits it in a binary tree.
All leaves of a B-tree are at the same depth. When an insert overfills a node, the node splits in two and its middle key moves up into the parent, so the tree only gets taller when the root itself splits. Because each node has hundreds of children, a tree with hundreds of millions of keys is only about four levels deep, so a lookup reads about four nodes, and fewer if the top levels are cached in memory. A balanced binary tree holding the same keys would be more than 25 levels deep.
B+ trees
Databases and file systems usually use the B+ tree variant. In a B+ tree only the leaves store the data, the inner nodes store only keys for routing, and the leaves are linked in order. This makes a range query cheap: the search finds the first matching leaf, and the query then follows the links to the next leaves without going back up the tree. When you add an index to a database column, the database builds a B+ tree.
When you do not need a balanced tree
A balanced tree is the right tool only when you need both sorted order and frequent changes. If you only need lookups by key, a hash table is simpler and averages O(1), but it cannot find the next larger key or list keys in a range. If you only need the smallest or largest element, a heap is simpler. If the data is built once and rarely changes, a sorted array with binary search gives the same O(log n) lookups with less code and less memory. If the keys are already sorted, you can build a perfectly balanced tree directly by making the middle key the root and repeating on each half.
Pitfalls when implementing balanced trees
In the interview
Problems rarely say "balanced tree". The signals are a need to keep a changing set of values in sorted order and to ask ordered questions about it: the smallest key greater than x, the largest key smaller than x, all keys in a range, or the k-th smallest. In Java or C++ you would use TreeMap or std::map and explain that it gives O(log n) for those operations.
Interviewers sometimes ask you to write AVL rotations, but more often they check that you understand the idea. These are the questions to expect:
- "Why does a binary search tree need balancing?" Its cost is proportional to its height, and sorted or nearly sorted input makes the height equal to the number of nodes. Balancing keeps the height at O(log n) whatever the input order.
- "What is a rotation and what does it preserve?" A rotation changes the parent and child relationship of two nodes and moves one subtree to a new parent. It preserves the inorder sequence, so the search order is still valid, and it takes O(1) time because only a few links change.
- "AVL tree or red-black tree?" An AVL tree is stricter, so its height is smaller and lookups are slightly faster, but it rotates more often on updates. A red-black tree allows a taller tree and does less work per update. Choose AVL for read-heavy data and red-black for a mix of reads and writes. Libraries mostly use red-black trees.
- "Why do databases use B-trees?" Disk reads dominate the cost, and a B-tree node with hundreds of keys makes the tree only three or four levels deep, so a lookup needs three or four reads. A binary tree would need a read per level, and it would be around 20 levels deep for a million keys.
- "How would you check that a binary tree is balanced?" Compute the height of each subtree recursively, and return a special value such as −1 as soon as any node is unbalanced. This visits each node once and takes O(n). Recomputing the height separately at every node takes O(n²) for a skewed tree, and interviewers watch for that.
- "How would you find the k-th smallest key in a balanced tree?" Store the size of each subtree in its node and update it during rotations, as the height is updated. At each node, compare k with the size of the left subtree to decide whether the answer is in the left subtree, the node itself or the right subtree. This takes O(log n).
- "Why not use a hash map instead?" A hash map has no order, so it cannot find the next larger key or return a range without looking at every key. If you never need order, a hash map is the better choice.
You insert 1, 2, 3 in order into an empty AVL tree. What is the root?
An AVL node is off by 2, and the path from it to the new value goes left and then right. What fixes it?
Why do databases use B-trees instead of red-black trees for indexes stored on disk?
What to practise next
When nodes can connect in any pattern, with cycles and several parents, the structure is a graph, and Graph Basics is the next lesson. To review the unbalanced version first, read Binary Search Trees.