Sub topic 2
Why balance matters: height controls cost
This chapter assumes you can read basic Python and that you already know how binary search tree (BST) search, insertion and deletion work. It also assumes you are comfortable with recursion, the terms root, leaf, subtree and height, and Big-O notation, including the difference between O(log n) and O(n). The goal is to show why the shape of a tree decides its speed, and what a "balanced" tree has to guarantee.
Height is the cost of every operation
A BST operation follows one path from the root downward. Search compares the key with each node and goes left or right. Insertion walks the same path until it finds an empty slot. Deletion first searches for the node, and in the two-child case it also walks down to find the in-order successor. In every case the work is proportional to the number of nodes on the path, and the longest possible path is the height of the tree.
This chapter uses these conventions:
- The height of an empty tree is 0.
- The height of a single node is 1.
- The height of any other node is 1 plus the larger of its children's heights.
So search, insert and delete all cost O(h), where h is the height. The number of keys, n, only matters through its effect on h. The rest of the tutorial is about keeping h small.
Best case: a full tree
A binary tree has at most 2^(k-1) nodes on level k, counting the root as level 1. A tree of height h therefore holds at most 2^h - 1 nodes. Solving this for h shows how short a tree of n nodes can be:
n ≤ 2^h - 1, so h ≥ log2(n + 1).
A well-shaped tree with a million keys has a height of about 20. A search then makes at most about 20 comparisons. Doubling the number of keys adds only one level.
Worst case: a linked list
The same ordering rules allow a very different shape. Insert the keys 1, 2, 3, 4, 5 in that order into an empty BST. Each new key is larger than everything already in the tree, so it goes to the right of the last node. The result is a chain:
Every node has only a right child, so the height equals n. Searching for 5 visits all five nodes, which is no better than scanning a linked list. Reverse-sorted input produces the mirror image, a chain leaning left.
This is not a rare accident. Sorted or nearly sorted input is common in practice: timestamps, auto-incrementing IDs, alphabetical imports, and data that was already sorted by an earlier step. A plain BST is fast for random insertion order and slow for the inputs that real systems often produce.
Measuring it
The following program inserts the same keys into a plain BST in two orders and reports the height. Both runs use the same code and the same data, and only the order differs.
import random
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(root, key):
"""Plain BST insert, written iteratively to avoid recursion limits."""
if root is None:
return Node(key)
cur = root
while True:
if key < cur.key:
if cur.left is None:
cur.left = Node(key)
return root
cur = cur.left
elif key > cur.key:
if cur.right is None:
cur.right = Node(key)
return root
cur = cur.right
else:
return root # ignore duplicates
def height(root):
"""Height computed with an explicit stack; empty tree is 0."""
if root is None:
return 0
best = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
best = max(best, depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return best
def build(keys):
root = None
for k in keys:
root = insert(root, k)
return root
n = 2000
sorted_keys = list(range(n))
shuffled_keys = sorted_keys[:]
random.seed(1)
random.shuffle(shuffled_keys)
print("sorted input: ", height(build(sorted_keys)))
print("shuffled input:", height(build(shuffled_keys)))The sorted run prints 2000, because the tree is a chain. The shuffled run prints a much smaller number, typically in the 20s. The exact figure for the shuffled case depends on the random seed. The minimum possible height for 2000 keys is 11, since 2^11 - 1 = 2047 is the first full-tree size that is at least 2000.
Two implementation details matter here. The code is iterative because a recursive insert on the 2000-node chain would exceed Python's default recursion limit of about 1000 frames. That limit is itself a symptom of the problem: depth is cost, and it is also stack space.
How much worse is the worst case?
The gap between the two shapes grows quickly with n.
| Keys (n) | Balanced height (about log2 n) | Chain height (n) |
|---|---|---|
| 1,000 | 10 | 1,000 |
| 1,000,000 | 20 | 1,000,000 |
| 1,000,000,000 | 30 | 1,000,000,000 |
At a million keys, a search in a chain makes up to a million comparisons, against about twenty in a balanced tree. That is a factor of fifty thousand. Building a chain by inserting n sorted keys costs 1 + 2 + ... + n comparisons in total, which is O(n²). For 100,000 keys that is about five billion steps, so the program would appear to hang.
Random order is not a guarantee
Random insertion order gives a tree whose expected height is O(log n), about 2 ln n for the average node depth, and the worst-case height stays close to a small constant times log2 n. This is a statement about averages over random orders. It does not help in these situations:
- The input order is not random. Sorted, reverse-sorted, and "sawtooth" patterns all produce tall trees.
- An adversary controls the input. A client that can choose keys can force a chain, which turns a slow lookup into a denial-of-service lever.
- Deletions are mixed in. Repeatedly deleting one side of the tree, such as always using the in-order successor, tends to skew shape over time even if the initial insertion order was random.
- The data set changes over a long time. A tree that was fine at build time can drift.
Software that must meet a latency bound needs a worst-case guarantee, not an average-case hope. That is what balanced trees provide.
What "balanced" has to mean
A balanced tree is a BST with an extra rule, called an invariant, that is restored after every insertion and deletion. The rule has to satisfy two requirements:
- It forces the height to be O(log n). Any tree obeying the rule has height at most some constant times log2 n.
- It is cheap to restore. After one insertion or deletion, repairing the rule must take about O(log n) time, so the repair does not cost more than the operation it protects.
If you demand perfect balance, where every level is completely full, the first requirement is met but the second is not. A tree of 2^h - 1 nodes is the only perfect shape for that size, and adding one key breaks it. Restoring perfection can mean rebuilding much of the tree, which costs O(n). Practical designs relax the rule just enough to keep repairs local. They trade a slightly taller tree for cheap maintenance.
The two designs in this tutorial relax the rule in different ways:
- AVL trees require that at every node, the heights of the left and right subtrees differ by at most 1. This is strict, so the tree stays very short.
- Red-black trees color each node red or black and enforce rules about colors. This allows paths to differ in length by up to a factor of two, so the tree can be taller, but repairs need fewer structural changes.
Both guarantee O(log n) height, so search, insert and delete are O(log n) in the worst case.
The repair tool
Both designs fix their invariants with the same small operation, the rotation. A rotation rearranges a few nodes locally, changes heights by a bounded amount, and leaves the in-order sequence of keys untouched, so the BST ordering still holds. The next chapter develops rotations in detail. For now, the important facts are that a rotation takes O(1) time and that it changes the shape without breaking order.
Common mistakes
- Counting height in edges in one place and nodes in another. Pick one convention and keep it. This tutorial uses nodes, so an empty tree is 0 and a leaf is 1. A mismatch silently shifts every balance calculation by one.
- Assuming a short average depth means a short tree. A tree can have most nodes near the root and still contain one very long path. Operations on keys at the end of that path stay slow.
- Trusting random order in tests. A test that inserts shuffled data will never expose a degenerate case. Always include sorted and reverse-sorted inserts.
- Using recursion on unbalanced trees. Depth limits, such as Python's recursion limit, turn a performance problem into a crash.
Check your understanding
Exercise
You insert the keys 10, 20, 30, 40, 50, 60, 70 in that order into an empty plain BST. What is the height of the resulting tree, using the convention that a single node has height 1? What would the minimum possible height be for these 7 keys, and what shape achieves it?
Show answer
The tree is a right-leaning chain, so the height is 7. The minimum possible height for 7 keys is 3, because 2^3 - 1 = 7. It is achieved by a full tree with 40 at the root, 20 and 60 as its children, and 10, 30, 50 and 70 as the leaves.
Exercise
A plain BST receives n keys in sorted order. How many key comparisons does it make in total to build the tree, and what is the Big-O of that total? Why does a balanced tree do better?
Show answer
The k-th insertion walks past the k-1 existing nodes, so the total is 0 + 1 + ... + (n-1) = n(n-1)/2 comparisons, which is O(n²). A balanced tree keeps the height at O(log n), so each insertion costs O(log n) and the total is O(n log n).
Exercise
Why is "keep the tree perfectly full at all times" not a practical balance rule?
Show answer
A perfectly full tree exists only when n is 2^h - 1 for some h. Adding or removing one key can force a rebuild of a large part of the tree, which costs O(n) per operation. A practical rule must be cheap to repair, so it allows some slack in the shape in exchange for local, O(log n) repairs.