Sub topic 8
Inserting Intervals
This chapter assumes you can write a recursive binary search tree (BST) insert and that you know the max-endpoint invariant from the previous chapter. The invariant says each node's max field holds the largest high endpoint in that node's subtree.
The Idea
Insertion is a normal BST insert with one change. The tree is ordered by each interval's low endpoint. Every node on the path from the root to the new leaf gets a new subtree, so its max may need to grow. You fix max on the way back up the recursion.
A new leaf starts with max equal to its own high endpoint, because its subtree contains only itself.
The Code
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi # largest high endpoint in this node's subtree
self.left = None
self.right = None
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)
node.max = max(node.max, hi)
return node
def show(node):
# In-order traversal: intervals appear sorted by low endpoint.
if node is not None:
show(node.left)
print(f"({node.lo}, {node.hi}) max={node.max}")
show(node.right)
root = None
for lo, hi in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
root = insert(root, lo, hi)
show(root)The output is:
(5, 20) max=20
(10, 30) max=30
(12, 15) max=15
(15, 20) max=40
(17, 19) max=40
(30, 40) max=40Why One Line Is Enough
The line node.max = max(node.max, hi) runs on every node along the insertion path. Only those nodes gain a new descendant, so only their max values can change. Nodes off the path keep the same subtree and the same max.
You only compare against the new hi. The old node.max already covers everything that was in the subtree before, so no recomputation over the children is needed.
Duplicate low endpoints go to the right, because the else branch handles lo >= node.lo. This keeps the BST ordering consistent. Two intervals with the same lo but different hi can both be stored.
The Resulting Tree
Note that the root's max is 40 even though the root's own interval ends at 20. The value 40 came from (30, 40), two levels down.
Cost and Common Mistakes
Insertion visits one node per level, and each visit does constant work. The cost is O(h), where h is the tree height. With no balancing, h can reach n, for example when intervals arrive sorted by low endpoint. A later chapter covers rebalancing.
Common errors:
- Ordering by
hior by length. The BST key must belo. The search relies on this ordering. - Setting
maxonly at creation. Without the update on the way back up, ancestors keep stale values and searches will wrongly skip subtrees. - Updating
maxbefore the recursive call. This works for insertion, since the newhiis known up front. It breaks in deletion and rotations, wheremaxmust be recomputed from the children after they change.
Exercise
Starting from the tree above, you insert (8, 50). Which existing nodes change their max value, and to what?
Show answer
The insert path is 15 (go left, since 8 < 15), then 10 (go left, since 8 < 10), then 5 (go right, since 8 >= 5). The nodes (15, 20), (10, 30) and (5, 20) all get max=50. The new node (8, 50) is a right child of (5, 20) with max=50. Nodes (12, 15), (17, 19) and (30, 40) are off the path and keep their values.