Sub topic 2
Why balance matters: height controls cost
This chapter assumes you can already write BST search and insertion, you are comfortable with recursion and the terms root, leaf, subtree and height, and you can read Big-O and basic Python. Here we show why tree height decides the cost of every operation, and why ordinary inserts can wreck it.
Height is the cost
Search, insert and delete in a binary search tree (BST) all walk one path from the root down. They never visit two branches at the same level. The work is therefore proportional to the length of that path, and the longest possible path is the tree's height.
In this tutorial the height of an empty tree is 0 and the height of a single node is 1. So every operation costs O(h), where h is the height. What that means in terms of n, the number of keys, depends entirely on the tree's shape.
Two shapes, same keys
A binary tree with h levels holds at most 2^h - 1 nodes. Turning that around, the smallest height for n keys is the ceiling of log2(n + 1). A tree that achieves this is as short as it can be. At the other extreme, each node has only one child, and the tree is a linked list of height n.
The gap grows quickly with n.
| Keys (n) | Best height | Worst height |
|---|---|---|
| 1,000 | 10 | 1,000 |
| 1,000,000 | 20 | 1,000,000 |
| 1,000,000,000 | 30 | 1,000,000,000 |
A balanced tree turns a billion keys into at most 30 comparisons. A degenerate one turns the same search into a linear scan.
How a BST degenerates
A plain BST never reorganizes itself. Its shape is decided by the order in which keys arrive. Insert 1, 2, 3, ... in sorted order and each new key is larger than everything before it, so it always goes to the right of the last node. Reverse-sorted input degenerates the same way to the left. Sorted or nearly sorted input is common in practice: timestamps, auto-increment IDs and data loaded from an ordered file.
The program below builds both cases and measures them. It uses loops instead of recursion because a height-1000 chain would hit Python's default recursion limit.
import random
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(root, key):
if root is None:
return Node(key)
cur = root
while True:
if key < cur.key:
if cur.left is None:
cur.left = Node(key)
break
cur = cur.left
elif key > cur.key:
if cur.right is None:
cur.right = Node(key)
break
cur = cur.right
else:
break # duplicate: ignore
return root
def height(root):
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 = 1000
keys = list(range(1, n + 1))
print("sorted: ", height(build(keys))) # 1000
random.seed(7)
random.shuffle(keys)
print("shuffled:", height(build(keys))) # typically 20 to 30The sorted run prints 1000. The shuffled run lands around twice the ideal height of 10, which is still logarithmic. Random order is forgiving, but you rarely control the order in real input.
What a fix needs to do
We want a guarantee that holds for any sequence of inserts and deletes, not just lucky ones. A self-balancing tree adds two things to the ordinary BST:
- An invariant, a rule about shape that bounds the height by O(log n).
- A repair step after each insert or delete that restores the invariant using only local changes.
The repair must be cheap. If restoring balance meant rebuilding the whole tree, we would have traded one O(n) problem for another. The tools are rotations, which are covered in the next chapter. AVL trees and red-black trees choose different invariants. AVL trees keep heights strictly close together. Red-black trees allow looser shapes using color rules.
Exercise
A BST receives the keys 10, 20, 30, 40, 50 in that order. What is its height, and what is the smallest height any BST holding those five keys could have?
Show answer
The keys arrive in increasing order, so each one becomes the right child of the previous one. The tree is a chain of height 5. The smallest possible height is the ceiling of log2(5 + 1) = 3, for example with 30 at the root, 20 and 40 as its children, and 10 and 50 below them.