Sub topic 8
Inserting Intervals
This chapter assumes you can write a recursive binary search tree (BST) insert. It also assumes you know the max-endpoint invariant from the previous chapter: each node stores max, the largest high endpoint in its subtree. Here you will see how insertion keeps that invariant true, and what goes wrong when it doesn't.
The ordering rule
An interval tree is a BST whose key is the low endpoint. The high endpoint is payload. The only extra work is keeping max correct.
The invariant for every node n is:
n.max = max(n.hi, n.left.max, n.right.max)
Missing children are ignored. A new leaf starts with max = hi, because its subtree contains only itself.
The insertion algorithm
The insert walks down exactly as a normal BST insert does, comparing the new lo with each node's lo. It places the new node at a null slot. On the way back up, each ancestor folds the new hi into its own max.
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 lo > hi:
raise ValueError("interval must satisfy 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 nodeThree details matter.
- Return value.
insertreturns the subtree root, and the caller reassigns it (node.left = insert(...)). This is how the new leaf gets attached. - Update with
max. The linenode.max = max(node.max, hi)takes the larger of the old and new values. Insertion can only add an interval, so a subtree's max can only grow or stay the same. - Validation. The
lo > hicheck rejects malformed input at the boundary. The overlap test assumeslo <= hi, so a reversed interval would silently break searches later.
A worked trace
Insert these six intervals in order: (15,20), (10,30), (17,19), (5,20), (12,15), (30,40).
| Insert | Path taken | `max` changes |
|---|---|---|
| (15,20) | becomes root | root max = 20 |
| (10,30) | 10 < 15, goes left | root max 20 → 30; new node max = 30 |
| (17,19) | 17 ≥ 15, goes right | root max stays 30; new node max = 19 |
| (5,20) | left of 15, then left of 10 | no ancestor changes (20 ≤ 30) |
| (12,15) | left of 15, then right of 10 | no ancestor changes (15 ≤ 30) |
| (30,40) | right of 15, then right of 17 | node 17: 19 → 40; root: 30 → 40 |
The final tree looks like this.
Check the invariant at the root. Its own hi is 20, its left subtree's max is 30, and its right subtree's max is 40. The largest of these is 40, which matches.
Notice that the largest max does not always sit at the deepest node. The interval (10,30) has a high endpoint larger than its parent's, and it reaches the root's max only because it is in the root's subtree.
Checking the invariant in code
When you modify tree code, a checker that recomputes every max from scratch catches bugs quickly. This program runs the trace above and verifies the result.
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi
self.left = None
self.right = None
def insert(node, lo, hi):
if lo > hi:
raise ValueError("interval must satisfy 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 check(node):
# Recomputes max bottom-up and asserts it matches the stored value.
if node is None:
return float("-inf")
expected = max(node.hi, check(node.left), check(node.right))
assert node.max == expected, (node.lo, node.hi, node.max, expected)
return expected
def in_order(node):
if node is None:
return []
return in_order(node.left) + [(node.lo, node.hi, node.max)] + in_order(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)
check(root)
for item in in_order(root):
print(item)The output lists the intervals sorted by low endpoint, with their max values:
(5, 20, 20)
(10, 30, 30)
(12, 15, 15)
(15, 20, 40)
(17, 19, 40)
(30, 40, 40)Duplicates and ties
Two intervals can share a low endpoint. The code above sends an equal lo to the right subtree. Any consistent rule works, because later searches never rely on lo being unique. They rely only on the in-order sequence being sorted by lo, and any tie rule preserves that.
Identical intervals, such as two copies of (5,9), are stored as two nodes. If you want set semantics, check for an exact match before inserting. Decide this deliberately, because a calendar may allow two identical bookings while an index of unique ranges may not.
Cost
Insertion visits one node per level on the way down and updates one per level on the way up. That is O(h) time, where h is the tree height. It also uses O(h) stack space in the recursive version and adds one node, so the structure grows by O(1) per insert.
Without balancing, h depends on insertion order. Inserting intervals already sorted by lo produces a chain, so h = n and each insert is O(n). A later chapter fixes this with rotations. Rotations change which nodes are ancestors, so they must recompute max for the nodes they move.
Python's recursion limit is about 1000 frames by default. A degenerate tree of that depth will raise RecursionError. A balanced tree avoids this, as does an iterative insert that records the path in a list and updates max while walking it backwards.
Common errors
- Overwriting instead of maximizing. Writing
node.max = hireplaces a larger existing value with a smaller one. Searches then prune subtrees that contain overlaps. - Updating only the new node. If ancestors keep stale
maxvalues, a new interval with a largehiis invisible to searches that prune bymax. - Forgetting to reassign the child. Calling
insert(node.left, lo, hi)withoutnode.left = ...loses the new node whenever the slot was empty. - Keying on
hi. The tree must be ordered bylo. Ordering byhimakes themaxpruning rule in the search chapter wrong. - Mutating a stored interval. Changing
loin place breaks the BST order. Changinghiin place breaksmaxon every ancestor. Delete and reinsert instead.
Exercise
Starting from an empty tree, insert (8,9), then (3,50), then (6,7). Give the max value stored at each of the three nodes afterward.
Show answer
(8,9) is the root. (3,50) goes left, so the root's max becomes 50 and the node (3,50) has max 50. (6,7) goes left of the root (6 < 8), then right of (3,50) (6 ≥ 3). It has max 7. Its parent (3,50) keeps max 50, and the root keeps max 50. Final values: root (8,9) = 50, (3,50) = 50, (6,7) = 7.
Exercise
A teammate changes the last line of insert to node.max = hi. Which inputs expose the bug, and what symptom would a search show?
Show answer
Any insert where an ancestor's existing max exceeds the new hi exposes it. For example, inserting (10,30) and then (5,20) overwrites the root's max of 30 with 20. The tree then claims nothing in the root's subtree reaches above 20, so a search for a query like (25,28) prunes the subtree and returns None even though (10,30) overlaps it. The check function would fail with an assertion on the first such insert.