Balanced Trees: AVL & Red-Black
Data Structures & Algorithms · Trees & Heaps · Advanced · 28 min
See why a plain BST can collapse into a list, measure balance with heights, repair it with AVL rotations (LL, RR, LR, RL), and know why red-black trees power TreeMap and std::map.
A mobile hanging from the ceiling. When one arm gets too heavy it tilts, so you slide the pivot point over and it hangs level again. Nothing is removed, the same pieces just hang from a different point.
The idea in everyday words
Imagine a family tree drawn on paper where everyone keeps adding children only on the right. Soon it is a single long chain running off the page and finding anyone means reading the whole chain. A balanced tree is a strict editor who, every time one side gets two levels deeper than the other, lifts the middle person up and redraws that small corner so the picture stays wide and short.
The problem: a BST is only as fast as it is short
BST search, insert and delete cost O(h), the height of the tree. With random keys h stays around log n. But real data is often sorted or nearly sorted: auto-increment IDs, timestamps, alphabetical imports.
Insert 1, 2, 3, 4, 5 into a plain BST:
1
\
2
\
3
\
4
\
5
Every key goes right. The "tree" is a linked list with height 5, and searching a million sorted keys takes a million steps instead of about 20.
A self-balancing tree does a tiny bit of repair work after each insert or delete so that the height always stays O(log n), whatever order the keys arrive in.
Height and balance factor
- Height of a node = number of nodes on the longest path down to a leaf. A leaf has height 1, an empty child has height 0.
- Balance factor = height(left) - height(right).
The AVL rule (named after Adelson-Velsky and Landis, 1962): at every node the balance factor must be -1, 0 or +1. The two sides may differ by at most one level.
| Balance factor | Meaning |
|---|---|
| 0 | both sides equally tall |
| +1 / -1 | one side is one level taller: allowed |
| +2 / -2 | broken: rotate to fix |
Why this is enough: the smallest AVL tree of height h has N(h) = 1 + N(h-1) + N(h-2) nodes, which grows like the Fibonacci numbers, so exponentially. Flip it around: n nodes means height at most about 1.44 · log₂ n. Always logarithmic.
Each node stores its height, and after an insert we update heights on the way back up, checking each balance factor.
Rotations: redraw a corner, keep the order
A rotation is a local rearrangement of 2 nodes and 3 subtrees. It changes the shape but keeps the inorder (sorted) order, so the BST rule still holds.
Right rotation at y (used when y's left side is too tall):
y x
/ \ / \
x C ==> A y
/ \ / \
A B B C
Inorder before: A, x, B, y, C. After: A, x, B, y, C. Same order. Only three links change, so a rotation is O(1).
Note subtree B: it was x's right child (bigger than x, smaller than y), and it becomes y's left child (still bigger than x, smaller than y). That is the one line people forget.
A left rotation is the mirror image.
The four cases: LL, RR, LR, RL
After inserting a key, walk back up. At the first node whose balance factor is ±2, look at the path the new key took from that node:
| Case | Path from the broken node | Fix |
|---|---|---|
| LL | left, then left | one right rotation at the node |
| RR | right, then right | one left rotation at the node |
| LR | left, then right (a bend) | left-rotate the left child, then right-rotate the node |
| RL | right, then left (a bend) | right-rotate the right child, then left-rotate the node |
How to remember it: a straight line (LL, RR) needs one rotation. A bend (LR, RL) needs two: the first rotation straightens the bend into a line, the second fixes the line.
Example RL: insert 10, 30, 20. At 10, the key went right (30) then left (20). Right-rotate 30 to get the line 10 → 20 → 30, then left-rotate 10. Result: 20 at the root with 10 and 30 as children.
After an insert, one fix (single or double rotation) is enough to restore the whole tree, because the subtree returns to the height it had before the insert.
Red-black trees: the practical choice
Most standard libraries use a red-black tree instead of AVL. Every node is coloured red or black, with these rules:
- The root is black.
- A red node never has a red child.
- Every path from a node down to an empty spot passes the same number of black nodes.
Rules 2 and 3 together mean the longest path is at most twice the shortest, so height ≤ 2 · log₂(n + 1). Still O(log n).
| AVL | Red-black | |
|---|---|---|
| Balance | strict (heights differ by ≤ 1) | looser (longest path ≤ 2 × shortest) |
| Lookups | slightly faster (shorter tree) | slightly slower |
| Insert | at most 2 rotations (one single or one double fix) | at most 2 rotations, plus cheap recolouring |
| Delete | may rotate at every level on the way up: O(log n) rotations | at most 3 rotations, plus cheap recolouring |
| Used in | read-heavy indexes, some databases | Java TreeMap / TreeSet, C++ std::map / std::set, the Linux kernel |
In an interview you are rarely asked to code a red-black tree. You are expected to know: a plain BST can degrade to O(n), balanced trees guarantee O(log n), and TreeMap / std::map give you an ordered map with floor, ceiling and range queries in O(log n). Python has no built-in balanced tree. People use bisect on a sorted list (searching is O(log n), but insort still shifts items, so each insert or delete is O(n)) or the third-party sortedcontainers package. Note that heapq is not a replacement: a heap only gives you the minimum quickly, with no floor, ceiling, range queries or fast delete of any key.
Step by step
- Insert 10, 20:
10 is the root. 20 goes right. Balance factor of 10 is 0 - 1 = -1: allowed.
- Insert 30: RR case:
30 goes right of 20. Now 10 has balance 0 - 2 = -2. The path from 10 is right, right: a straight line. One left rotation at 10 makes 20 the root with children 10 and 30.
- Insert 40, 50: RR again:
40 goes under 30, then 50 under 40. Node 30 becomes -2 (right, right). Left-rotate at 30: 40 takes its place with children 30 and 50. Tree: 20 → (10, 40 → (30, 50)).
- Insert 25: walk back up:
25 goes 20 → 40 → 30 → left of 30. Going back up: 30 has +1, 40 has +1, but 20 has 1 - 3 = -2. Broken at 20.
- Spot the bend: RL:
From 20 the key went right (to 40) then left (to 30). A bend, so two rotations. First right-rotate 40: 30 moves up with 25 on its left and 40 on its right.
- Second rotation:
Now it is a straight right-right line from 20, so left-rotate 20. 30 becomes the root: left subtree 20 → (10, 25), right subtree 40 → (_, 50).
- Result:
Preorder: 30, 20, 10, 25, 40, 50. Height 3 for 6 keys. A plain BST with the same inserts would be height 5.
Code example
class Node:
def __init__(self, key):
self.key, self.left, self.right, self.height = key, None, None, 1
def h(n):
return n.height if n else 0
def fix(n): # recompute height from the children
n.height = 1 + max(h(n.left), h(n.right))
def rotate_right(y): # y's left child x moves up
x = y.left
y.left = x.right # x's right subtree changes parent
x.right = y
fix(y); fix(x) # y is lower now, so fix it first
return x
def rotate_left(x): # mirror image
y = x.right
x.right = y.left
y.left = x
fix(x); fix(y)
return y
def insert(n, key):
if n is None:
return Node(key)
if key < n.key:
n.left = insert(n.left, key)
elif key > n.key:
n.right = insert(n.right, key)
else:
return n # duplicate: ignore
fix(n)
bal = h(n.left) - h(n.right) # balance factor
if bal > 1: # left side too tall
if key > n.left.key: # LR: bend, straighten it first
n.left = rotate_left(n.left)
return rotate_right(n) # LL: one right rotation
if bal < -1: # right side too tall
if key < n.right.key: # RL: bend, straighten it first
n.right = rotate_right(n.right)
return rotate_left(n) # RR: one left rotation
return n
def avl_preorder(values):
root = None
for v in values:
root = insert(root, v)
out = []
def pre(n):
if n:
out.append(n.key); pre(n.left); pre(n.right)
pre(root)
return out
def plain_insert(n, key): # ordinary BST, no balancing
if n is None:
return Node(key)
if key < n.key:
n.left = plain_insert(n.left, key)
else:
n.right = plain_insert(n.right, key)
fix(n)
return n
print("AVL of 1..7, preorder:", avl_preorder([1, 2, 3, 4, 5, 6, 7]))
plain = avl = None
for k in range(1, 101): # 100 keys in sorted order
plain = plain_insert(plain, k)
avl = insert(avl, k)
print("sorted 1..100 -> plain BST height:", h(plain), "| AVL height:", h(avl))Complexity
- Time: O(log n) per insert, delete and search: the height is at most about 1.44 log₂ n, and fixing balance touches only the nodes on one root-to-leaf path, with O(1) work per rotation
- Space: O(n) for the nodes (plus one height or colour field each) and O(log n) recursion stack
Interview tips
When you claim O(log n) for a BST operation, add 'if the tree is balanced, for example AVL or red-black'. It shows you know the degenerate case.
Be able to draw a single right rotation and say which subtree changes parent. That is the most common whiteboard question here.
Know the four cases by their shape: straight line, one rotation; bend, two rotations.
Explain why libraries pick red-black: both need at most 2 rotations on insert, but a red-black delete needs at most 3 while an AVL delete may rotate at every level. AVL is a bit faster for lookups because it is more strictly balanced.
In Java reach for TreeMap (floorKey, ceilingKey, subMap); in C++ std::map (lower_bound); in Python sortedcontainers, or bisect on a sorted list if inserts are rare (each insort is O(n)). A heap is not an ordered map.
Challenge: Build an AVL Tree
Insert the values one at a time into an empty AVL tree (ignore duplicates), rebalancing with rotations after each insert. Return the preorder traversal (node, left, right) of the final tree.
Example: avl_preorder([10, 20, 30, 40, 50, 25]) → [30, 20, 10, 25, 40, 50]
A plain BST would give [10, 20, 30, 25, 40, 50], a lopsided tree of height 5.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Balanced Binary Tree (Easy)
- Convert Sorted Array to Binary Search Tree (Easy)
- Balance a Binary Search Tree (Medium)
- AVL tree visualizer (USFCA)
More in Trees & Heaps
Previous: Binary Search Trees · Next: Heaps & Priority Queues