Sub topic 2
Augmenting a Tree with Extra Information
This chapter assumes you know binary search tree (BST) ordering, recursion, and Big-O notation. We will store closed intervals, such as [10, 30], where both endpoints are included.
Augmenting a Tree with Extra Information
A BST can order intervals by their low endpoint. However, ordering alone does not reveal whether a subtree contains an interval that reaches a query interval.
An augmented tree is a tree whose nodes store extra information derived from their subtrees. The extra information lets searches prune branches without checking every node.
For interval trees, each node stores max, the largest high endpoint in its entire subtree.
The Max-Endpoint Invariant
The max-endpoint invariant is:
> For every node, node.max equals the largest hi value among that node and all nodes below it.
For a leaf containing [15, 20], max is 20. For an internal node, max summarizes both children and the node itself. This summary supports fast overlap searches.
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,
node.left.max if node.left else float("-inf"),
node.right.max if node.right else float("-inf"))
return nodeInserting Intervals
Insertion follows ordinary BST ordering. After recursive insertion returns, the code recomputes max on every ancestor along the path back to the root.
If a balanced tree has height O(log n), insertion takes O(log n). An unbalanced tree can degrade to O(n).
Searching for One Overlapping Interval
Two closed intervals [a, b] and [c, d] overlap when a <= d and c <= b.
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 NoneIf the left subtree's max is at least lo, that subtree might contain an overlap, so the search goes left. Once the current interval has already been tested, returning any overlap from the left makes searching the right unnecessary.
If the left subtree's maximum is below lo, every interval there ends too early. The search safely skips that subtree and goes right.
Exercise
What does find_overlap return for a query interval of [21, 23] when the tree contains [15, 20] and [10, 30]?
Show answer
It returns [10, 30], because the intervals overlap.