Sub topic 13
Keeping the Tree Balanced
This chapter assumes you know how a binary search tree (BST) works, what tree height means, and how the max-endpoint invariant and insertion from the earlier chapters work. It also assumes you can read short Python code.
Why balance matters
Every operation on an interval tree costs time proportional to the tree's height. Intervals are ordered by their low endpoint, so inserting them in sorted order builds a chain. A chain of n nodes has height n, and the search degrades to a linear scan, which is the cost we set out to avoid.
A balanced tree keeps the height at O(log n). Self-balancing trees such as AVL trees and red-black trees do this with rotations. A rotation is a local rewiring of a few pointers that changes the tree's shape but keeps the in-order sequence of keys.
What a rotation does to max
A rotation moves nodes, so the subtree under each moved node changes. The max field is computed from a node's own high endpoint and its children's max values. After a rotation it is stale for the two nodes whose children changed.
The fix has two parts:
- Recompute max for the node that moved down first. It now sits below the other node.
- Then recompute max for the node that moved up, which now depends on the lower node's fresh value.
Nodes outside the rotated pair keep their subtrees, so their max values stay valid. Each rotation therefore adds only constant work.
Rotations with max maintenance
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi
self.left = None
self.right = None
def update(node):
node.max = node.hi
if node.left is not None:
node.max = max(node.max, node.left.max)
if node.right is not None:
node.max = max(node.max, node.right.max)
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update(x) # x moved down, so fix it first
update(y) # y is the new subtree root
return y
def rotate_right(y):
x = y.left
y.left = x.right
x.right = y
update(y)
update(x)
return x
# A right-leaning chain: 10 -> 20 -> 30
a, b, c = Node(10, 12), Node(20, 50), Node(30, 35)
b.right = c
update(b)
a.right = b
update(a)
root = rotate_left(a)
print(root.lo, root.left.lo, root.right.lo) # 20 10 30
print(root.left.max, root.max) # 12 50After the rotation, node 10 has max 12 because it no longer has the high-endpoint 50 below it. The new root keeps max 50.
Where rotations are triggered
- Insertion: after the recursive insert returns, update max, check the balance rule, and rotate if needed. A single insertion needs at most two rotations in an AVL tree.
- Deletion: the same repair runs on every node along the path back to the root. Deletion may need O(log n) rotations.
Always call update before checking balance on the way up. Otherwise the rotation decisions and the max values can disagree.
Exercise
Exercise
In rotate_left, what goes wrong if you call update(y) before update(x)?
Show answer
Node y becomes the parent of x after the pointer changes, so y's max depends on x's max. Updating y first reads x's stale value, and y ends up with an incorrect max. x must be updated first, because its children are final and its max does not depend on y.