Section 14.10

Balanced search tree

Definition

A balanced search tree is a search tree that restores a shape rule after every insertion and removal, so that its height, the number of nodes on its longest downward path, stays within a constant factor of log2n\log_2 n for nn keys. The usual form is a binary search tree: each node holds one key and up to two children, with smaller keys in its left subtree and larger keys in its right. Since a search follows one downward path, every operation takes at most a constant times log2n\log_2 n steps.

The idea

Insert the keys 1, 2, 3, 4, 5, 6 and 7, in that order, into a plain binary search tree. Each new key is larger than every key already present, so it becomes the right child of the previous key, and the tree is a chain of 7 nodes. A search for 7 compares it with all 7 keys. The ordering rule still holds, but the tree is no better than a linked list §14.6. Sorted insertion is common, not an accident: timestamps, sequence numbers and identifiers handed out in increasing order all arrive sorted. With one million keys inserted in order, a search can take one million comparisons, while a tree of the best shape needs at most 20, because 20 levels hold 220−1=1,048,5752^{20} - 1 = 1{,}048{,}575 nodes.

A search in a well-shaped tree works like guessing a number from 1 to 1,000 when told “higher” or “lower”: each comparison discards about half of the remaining candidates, so about log21000≈10\log_2 1000 \approx 10 comparisons suffice. A shape rule does not demand exact halves. It only forbids any part of the tree from growing much deeper than the rest, and that is enough to keep every path short. Insertions and removals can break the rule near the place they change, so each update repairs the shape along the path it touched, using rotations, small rearrangements that keep the keys in order.

How it works

The root is the top node, and an absent child is a missing left or right child. A binary search tree supports three basic steps.

  1. Search. Start at the root and compare the target with the node’s key. If they are equal, stop: found. If the target is smaller, move to the left child; if larger, to the right child. If that child is absent, stop: the key is not in the tree.

  2. Insert. Search for the new key. The search ends at an absent child; attach a new node holding the key there. The ordering rule still holds.

  3. Repair. Walk back up the search path toward the root and check the shape rule at each node. Where it fails, apply rotations. Removal ends with the same repair walk.

A rotation changes the shape of a small part of the tree without changing the order of its keys. Take a node yy whose left child is xx. Let AA be the left subtree of xx, BB the right subtree of xx, and CC the right subtree of yy. A right rotation at yy puts xx in the place of yy, makes yy the right child of xx, and moves BB to become the left subtree of yy. Listed from smallest to largest, the keys are A,x,B,y,CA, x, B, y, C both before and after, so every search still finds every key. A left rotation is the mirror image. A rotation changes three child references and takes a fixed number of steps.

Two shape rules are in common use.

Balanced multiway trees, such as B-trees, apply the same idea with many keys per node and all bottom nodes at the same depth; databases and file systems use them because one node can fill one block of a disk.

Worked example

Insert the keys 1 to 7 in increasing order into an AVL tree. A node is out of balance when its two subtrees differ in height by 2 or more; the repair rotates at the lowest such node on the path.

  1. Insert 1, then 2: node 2 becomes the right child of 1. At node 1 the subtree heights are 0 on the left and 1 on the right, a difference of 1, which is allowed.

  2. Insert 3 as the right child of 2. At node 1 the heights are now 0 and 2. A left rotation at node 1 makes 2 the root, with 1 on its left and 3 on its right. The keys still read 1, 2, 3 in order, and the height drops from 3 to 2.

  3. Insert 4 as the right child of 3. Node 3 has heights 0 and 1, and node 2 has heights 1 and 2: both allowed.

  4. Insert 5 below 4. Node 3 now has heights 0 and 2. A left rotation at 3 puts 4 in its place, with children 3 and 5.

  5. Insert 6 below 5. Node 2 now has a left subtree of height 1, node 1 alone, and a right subtree of height 3, the path 4, 5, 6. A left rotation at 2 makes 4 the root. Node 2 becomes the left child of 4, keeps 1 on its left, and takes 3, formerly the left child of 4, on its right.

  6. Insert 7 below 6. Node 5 now has heights 0 and 2. A left rotation at 5 puts 6 in its place, with children 5 and 7.

The result is the best possible shape: 4 at the root, 2 and 6 below it, and 1, 3, 5 and 7 at the bottom, a height of 3. A search for 7 compares it with 4, 6 and 7, which is 3 comparisons instead of the 7 needed in the chain. Four rotations were needed for seven insertions.

Stated precisely

Let the height hh of a tree be the number of nodes on its longest path from the root down, so an empty tree has height 0 and a single node has height 1, and let nn be the number of keys. A binary tree of height hh has at most 1+2+4+…+2h−1=2h−11 + 2 + 4 + \dots + 2^{h-1} = 2^h - 1 nodes, so every binary tree with nn keys has h≥log2(n+1)h \ge \log_2 (n + 1). For n=7n = 7 this gives h≥log28=3h \ge \log_2 8 = 3, the height reached in the example. Without a shape rule the only upper bound is h≤nh \le n, the chain.

AVL bound. Let N(h)N(h) be the fewest nodes that an AVL tree of height hh can have. The sparsest such tree has a root, one subtree of height h−1h - 1 and, as the rule allows, one of height h−2h - 2, each as sparse as possible. Hence N(0)=0N(0) = 0, N(1)=1N(1) = 1 and N(h)=1+N(h−1)+N(h−2)N(h) = 1 + N(h - 1) + N(h - 2). The values are 0, 1, 2, 4, 7, 12, 20, 33, growing like the Fibonacci numbers, by a factor of about 1.618 per level. Turning this growth around gives h<1.45log2(n+2)h < 1.45 \log_2 (n + 2) for every AVL tree with nn keys.

Red-black bound. Let bb be the number of black nodes on each path from the root down to an absent child; the rules make it the same for every such path. By induction on the height, a red-black tree with this bb has at least 2b−12^b - 1 nodes. No red node has a red child, so at least half the nodes on any path are black, and b≥h/2b \ge h / 2. Together, n≥2h/2−1n \ge 2^{h/2} - 1, which is h≤2log2(n+1)h \le 2 \log_2 (n + 1). For one million keys this allows at most 39 levels, against at least 20 for any binary tree.

Search, insertion and removal each follow one path and repair along it, so each takes at most a constant times hh steps, written O(logn)O(\log n), meaning at most a constant times logn\log n. This counts comparisons and reference changes. It assumes that comparing two keys takes a fixed number of steps, and that the keys follow a total order: any two keys compare as smaller, equal or larger, consistently, and the order of stored keys never changes while they are in the tree.

Limits and common mistakes

The ordering rule alone bounds nothing. A binary search tree whose updates do not restore a shape rule can become a chain, as the sorted insertion shows.

Balanced does not mean perfect. An AVL tree can be about 1.44 times as tall as the best shape, and a red-black tree up to twice as tall.

Steps are not time. Comparing two text keys costs time that grows with their length, and each move to a child may miss the processor’s cache, a small fast memory near the processor. For small collections, such as a few dozen keys, a sorted array §14.5 searched by binary search, or even a plain scan, is often faster and smaller, since every tree node carries two child references and its balance data.

Each insertion usually allocates a node. On a device that allocates from a fixed pool of nodes, the pool sets the limit, and an insertion can fail for lack of memory.

Rotations move nodes. A remembered position in the tree, such as an iterator (an object that steps through the keys in order), may become wrong after an update, and a thread that reads the tree during a rotation can see a half-finished shape. Use by several threads needs a lock or a design made for it.

Equal keys need one rule, such as “equal keys are rejected” or “equal keys go to the right”, applied in the same way by insertion, search and removal.

Some alternatives give weaker guarantees of a different kind. Treaps and skip lists keep paths short only with high probability, through random choices, and splay trees bound only the average cost over a sequence of operations. AVL and red-black trees bound every single operation.

A worst-case step count is not a deadline. A real-time system §6.34 also needs the time each step takes and the delays caused by interrupts §6.11 and other threads.

Questions answered

What invariant prevents a sorted insertion sequence from creating a linear chain?

A balance invariant prevents it: a shape rule that every node of the tree must satisfy and that every insertion and removal restores, using rotations, before it finishes. A rotation is a local rearrangement that changes the tree’s shape but keeps its keys in order. The ordering invariant of a binary search tree, smaller keys in a node’s left subtree and larger keys in its right subtree, does not prevent the chain, because a chain of increasing keys satisfies it. Two standard balance invariants are:

A chain of three increasing keys breaks both. Under the AVL rule, the top node has subtrees of heights 0 and 2. Under the red-black rules, no coloring of the chain is allowed: if the middle and bottom nodes are both red, a red node has a red child; otherwise the path from the top node down past the bottom node passes more black nodes than the path from the top node to its missing left child. Because the rule is restored after every insertion, sorted input yields a tree with nn keys whose height stays below 1.45log2(n+2)1.45 \log_2 (n + 2) for AVL and at most 2log2(n+1)2 \log_2 (n + 1) for red-black, instead of nn.

Related entries: Asymptotic complexity (§14.2), Linked list (§14.6), Directed acyclic graph (DAG) (§14.17), Interval data structure (§14.11). Further reading: [246].