Sub topic 12
Deleting Intervals
This chapter assumes you have read the earlier chapters on the max-endpoint invariant and insertion. It also assumes you know how ordinary binary search tree (BST) deletion works. Here you will extend that deletion so the max field stays correct, and you will see the cases where it goes wrong.
Why Deletion Needs Care
Insertion can only raise a max value, so node.max = max(node.max, hi) is enough on the way back up. Deletion can lower a max value. Suppose the interval (30, 40) is the only reason an ancestor stores max = 40. After you remove it, that ancestor must drop to a smaller value. If it keeps 40, the overlap search will follow a branch that no longer holds a matching interval. It will then miss intervals it should have found, or return None when an overlap exists elsewhere.
The invariant is: for every node, max equals the largest hi among the node itself and everything in its subtree. You can't repair it by comparing the old and new values. You recompute it from the node's own hi and its children's max values. Each recomputation costs O(1).
The Three Structural Cases
The tree is ordered by lo, so deletion follows the standard BST cases. The only addition is that every node on the path from the root to the change recomputes its max after the recursive call returns.
| Case | Action | Max update |
|---|---|---|
| Leaf | Return `None` to the parent | Parent recomputes from its remaining child |
| One child | Return the child to the parent | Parent recomputes using the child's existing `max` |
| Two children | Copy the in-order successor (smallest node in the right subtree) into this node, then delete the successor from the right subtree | This node recomputes after the recursive call |
Identifying the Interval to Delete
A BST of numbers identifies a key by its value. An interval tree can hold several intervals with the same lo, such as (5, 8) and (5, 20). Deleting by lo alone would remove the wrong one. The code below therefore identifies an interval by the pair (lo, hi).
The insertion code sends equal lo values to the right subtree. So when lo matches but hi does not, deletion continues to the right. This keeps the ordering rule intact: left subtree values are strictly smaller, and right subtree values are greater than or equal.
If the target is not in the tree, the recursion reaches None and returns it. The tree is unchanged, and every max is recomputed to the same value it already had.
Implementation
This listing is complete. It repeats Node, insert, and find_overlap from earlier chapters so you can run it as shown.
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 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 update_max(node):
# Recompute from scratch: own hi plus the children's stored maxima.
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 min_node(node):
while node.left is not None:
node = node.left
return node
def delete(node, lo, hi):
# Removes one stored interval equal to (lo, hi). Returns the new subtree root.
if node is None:
return None
if lo < node.lo:
node.left = delete(node.left, lo, hi)
elif lo > node.lo or hi != node.hi:
node.right = delete(node.right, lo, hi)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
succ = min_node(node.right)
node.lo, node.hi = succ.lo, succ.hi
node.right = delete(node.right, succ.lo, succ.hi)
update_max(node)
return 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
root = None
for lo, hi in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
root = insert(root, lo, hi)
print(root.max) # 40
root = delete(root, 30, 40) # leaf case
print(root.max) # 30, the max dropped
root = delete(root, 10, 30) # two-child case
print(root.max) # 20
print(find_overlap(root, 21, 23)) # NoneBefore the deletions, find_overlap(root, 21, 23) returned (10, 30). After (10, 30) is gone, nothing covers 21 to 23, and the search returns None. This works because every ancestor's max was recomputed.
Two details are worth noting.
- In the two-child case,
update_max(node)runs after the successor has been removed from the right subtree. Calling it earlier would use a stalenode.right.max. - The successor copy replaces both
loandhi. If you copied onlylo, the node would carry the wronghi, andmaxwould be computed from the wrong value.
Interaction with Rebalancing
Self-balancing trees (AVL, red-black) rebalance after deletion with rotations. A rotation changes which nodes are in each subtree, so the stored max values of the rotated nodes become wrong. Only the two nodes that change their children need fixing. The lower node must be updated first, because the upper node's new max depends on it.
def rotate_left(x):
y = x.right
x.right = y.left
y.left = x
update_max(x) # x is now the lower node, so it goes first
update_max(y) # y's subtree now contains x
return yA right rotation mirrors this. Subtrees hanging off the rotated nodes are unchanged as sets, so their max values stay valid. A rotation therefore adds O(1) work. Balancing is covered in the next chapter.
Cost
Deletion walks one root-to-node path, then possibly one more path down to find the successor. Each visited node does O(1) work. The total cost is O(h), where h is the tree height. With balancing, h is O(log n), so delete is O(log n). Without balancing, a sorted insertion order produces h close to n.
Common Errors
- Deleting by
loonly, which removes the wrong interval whenlovalues repeat. - Forgetting to recompute
maxafter a one-child splice. The returned child keeps its own correctmax, but the parent must still update. - Updating
maxbefore the recursive call returns, so it uses old child values. - Copying the successor's
lobut not itshi. - Mixing the equal-
lorule. If insertion sends ties right, deletion must also send ties right.
Exercise
A tree has the root (20, 25) with left child (10, 50) and right child (30, 35). The root's max is 50. You delete (10, 50), which is a leaf. What is the root's max afterward, and which step of the code produces it?
Show answer
The root's max becomes 35. The recursive call on the left subtree returns None, so the root's left is None. Then update_max(root) sets max to root.hi = 25 and takes the maximum with the right child's max, 35, giving 35. The stored value 50 is never reused.
Exercise
Why must delete recompute max from the node's own hi and its children's max values, instead of using max(node.max, hi) as insertion does?
Show answer
Insertion can only add a larger endpoint, so taking a maximum with the old value is safe. Deletion can remove the endpoint that produced the old max, so the old value may be too high. Only a fresh computation from the remaining node and children gives the correct value.