Sub topic 13
Keeping the Tree Balanced
This chapter assumes you know the max-endpoint invariant and the insertion and search code from the earlier chapters. It also assumes you know what tree height means and how a binary search tree (BST) rotation rearranges nodes.
Why Balance Matters Here
Every interval tree operation walks one path from the root downward. Insertion, single-overlap search and deletion all cost O(h), where h is the tree height. The plain insertion from earlier chapters never restructures the tree, so the order of arrivals decides h.
Suppose intervals arrive sorted by low endpoint, which is common for logs and calendars. Each new node goes to the right of the previous one. The tree becomes a linked list of height n, and every query degrades to the linear scan you set out to avoid.
| Insertion order | Height of an unbalanced tree | Cost of one search |
|---|---|---|
| Random | About 2 log n on average | O(log n) expected |
| Sorted by low endpoint | n | O(n) |
| Adversarial | n | O(n) |
The tree needs a rule that keeps h near log n whatever the input order.
Choosing a Balancing Scheme
You can add the max field to any balanced BST. Each scheme restores balance with rotations, and each rotation touches a constant number of nodes. The schemes differ in the bookkeeping they need.
- AVL tree. Every node stores its height. The heights of a node's two subtrees may differ by at most 1. Lookups are fast because the tree stays tightly balanced.
- Red-black tree. Every node stores one color bit, and a set of color rules bounds the height by 2 log2(n+1). It rotates less often than an AVL tree during updates. Most standard libraries use it.
- Treap or skip-style randomization. Random priorities give expected O(log n) height. The code is short, but the bound is probabilistic.
This chapter uses AVL because the rebalancing rule fits in a few lines. The part that matters for interval trees is the same in all schemes: any code that changes a node's children must recompute that node's max afterward.
What a Rotation Does to `max`
A rotation changes which node is the parent of which, but it does not add or remove intervals. Consider a right rotation at y, where x is y.left. Three subtrees A, B and C hang below them.
- Before:
yhas childrenxand C, andxhas children A and B. - After:
xhas children A andy, andyhas children B and C.
Only two nodes get a new set of descendants:
yloses A and gains nothing new. Its subtree is now B and C.xtakes over the whole old subtree ofy.
The subtrees A, B and C keep their own max values. The set of intervals under the new top node x equals the set that was under y, so the maximum of the whole subtree is unchanged. Ancestors above the rotation never need updating because of it.
You must recompute y first, because it is now the lower node and x depends on its value. Then recompute x.
An AVL Interval Tree
The update function derives both height and max from a node's own interval and its children. Rotations and rebalancing call it, so you never maintain max by hand in more than one place.
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi # largest high endpoint in this subtree
self.height = 1
self.left = None
self.right = None
def height(node):
return node.height if node else 0
def update(node):
node.height = 1 + max(height(node.left), height(node.right))
node.max = node.hi
if node.left and node.left.max > node.max:
node.max = node.left.max
if node.right and node.right.max > node.max:
node.max = node.right.max
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y) # lower node first
update(x)
return x
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x) # lower node first
update(y)
return y
def rebalance(node):
update(node)
balance = height(node.left) - height(node.right)
if balance > 1:
if height(node.left.left) < height(node.left.right):
node.left = rotate_left(node.left) # left-right case
return rotate_right(node)
if balance < -1:
if height(node.right.right) < height(node.right.left):
node.right = rotate_right(node.right) # right-left case
return rotate_left(node)
return node
def insert(node, lo, hi):
if node is None:
return Node(lo, hi)
if lo < node.lo:
node.left = insert(node.left, lo, hi)
else:
node.right = insert(node.right, lo, hi)
return rebalance(node)
def find_overlap(node, lo, hi):
while node is not None:
if node.lo <= hi and lo <= node.hi:
return (node.lo, node.hi)
if node.left is not None and node.left.max >= lo:
node = node.left
else:
node = node.right
return None
def check_max(node):
# Verifies the invariant everywhere. Returns the subtree's true max.
if node is None:
return float("-inf")
true_max = max(node.hi, check_max(node.left), check_max(node.right))
assert node.max == true_max
return true_max
root = None
for i in range(1000): # sorted input: worst case without balancing
root = insert(root, i * 10, i * 10 + 5)
check_max(root)
print(root.height <= 15) # True, an unbalanced tree would have height 1000
print(find_overlap(root, 12, 12)) # (10, 15)
print(find_overlap(root, 16, 19)) # None
print(find_overlap(root, 9993, 9994)) # (9990, 9995)The only change to insert is its last line. It used to be node.max = max(node.max, hi), and now it is return rebalance(node). The rebalance call recomputes max on every node along the path, whether or not a rotation happens. The search code does not change at all.
The Four Rotation Cases
rebalance handles every imbalance with one or two rotations.
| Case | Where the tall side is | Fix |
|---|---|---|
| Left-left | Left child's left subtree | One right rotation at the node |
| Left-right | Left child's right subtree | Left rotation at the left child, then right rotation at the node |
| Right-right | Right child's right subtree | One left rotation at the node |
| Right-left | Right child's left subtree | Right rotation at the right child, then left rotation at the node |
A double rotation is two single rotations. Each one runs update on the nodes it moves, so max stays correct at every step.
Deletion
Deletion follows the same pattern as insertion. Remove the node, then recompute and rebalance on the way back up. In a recursive implementation, each level assigns node.left = delete(node.left, ...) or the right-side equivalent and then returns rebalance(node).
Two details are specific to interval trees:
- A node with two children is usually replaced by its in-order successor, the leftmost node of the right subtree. If you copy the successor's
loandhiinto the node and then delete the successor, the copied values changenode.hi. Theupdatecall inrebalancethen recomputesmaxfrom the new values. Skipping that call leaves a stale, too-largemax, which makes searches slower. It can also leave an ancestor'smaxtoo small, which causes missed overlaps. - Removing an interval can lower
maxall the way up to the root. Every ancestor on the path must be recomputed, not just the parent.
Deletion can trigger up to O(log n) rotations, one per level. The total cost is still O(log n).
Cost After Balancing
AVL height is at most about 1.44 log2(n + 2). Each insertion does O(1) work per level, and it performs at most two rotations. update is O(1), so insertion, deletion and single-overlap search are all O(log n) in the worst case. Reporting all k overlaps stays O(k + log n)-style in practice, as the complexity chapter analyzes. Space is O(n) for the nodes, plus one integer for height and one for max per node.
Exercise
A right rotation at node y makes x = y.left the new subtree root. Which nodes need their max recomputed, and why do the ancestors of the subtree not need it?
Show answer
Only y and x need recomputing, y first because it is now the lower node and x's new children include it. The rotation neither adds nor removes intervals, so the set of intervals under the new root x equals the set that was under y. The maximum high endpoint of that set is unchanged, so the parent's max and all higher max values are still correct.
Exercise
You insert 1,000 intervals with increasing low endpoints into the unbalanced tree from earlier chapters. How many nodes might find_overlap visit for one query, and how does the AVL version change that?
Show answer
The unbalanced tree is a chain of height 1,000, so a query can visit about 1,000 nodes, the same as a linear scan. The AVL version keeps the height at about 10 to 15, so a query visits at most that many nodes.