Sub topic 6
Augmenting a Tree with Extra Information
This chapter assumes you know how a binary search tree (BST) orders keys, how insertion and search work, and what tree height means for running time. It also assumes you can read short recursive Python. Earlier chapters defined intervals and the overlap test, and showed that a linear scan costs O(n) per query. Here you learn the general technique that the interval tree uses: storing extra data in each node.
Why a plain BST is not enough
Suppose you store intervals in a BST ordered by their low endpoint. Insertion and exact lookup by low endpoint take O(h) time, where h is the tree height. An overlap query is a different question. At each node you must decide whether to go left, go right, or stop. The ordering by low endpoint says nothing about high endpoints, and the high endpoints decide whether an overlap exists.
Here is an example. Query the interval [60, 70] against a tree whose root is (50, 55), with (5, 100) somewhere in its left subtree. The root does not overlap the query. The low endpoint 5 is far below 60, so ordering alone suggests that nothing on the left can matter. But (5, 100) does overlap [60, 70]. To skip the left subtree safely, you need a fact about all the high endpoints in it, and the tree does not record that fact.
You could compute the fact on demand by scanning the subtree, but that scan is O(n) and you are back to the naive approach. The fix is to compute the fact once, store it in the node, and keep it current as the tree changes.
What augmentation means
Augmenting a data structure means adding a field to each node, beyond what the base structure needs, so that a new kind of query becomes fast. The base structure keeps working as before. The extra field only has to be maintained.
The idea applies to many problems. A field that stores the number of nodes in each subtree lets you find the k-th smallest key. A field that stores the sum of values in each subtree lets you answer range-sum queries. In an interval tree, the field stores a bound on the high endpoints in each subtree.
A worked example: subtree sizes
Before the interval case, here is the technique on a simpler field. Each node stores size, the number of nodes in the subtree rooted at it. With that field you can find the k-th smallest key in O(h) time, which a plain BST cannot do.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.size = 1 # nodes in the subtree rooted here, including this one
def size(node):
return node.size if node is not None else 0
def update(node):
# Recompute the augmented field from the node's children.
node.size = 1 + size(node.left) + size(node.right)
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
update(node) # runs on the way back up, children first
return node
def select(node, k):
# Returns the k-th smallest key, counting from 0, or None if k is out of range.
while node is not None:
left = size(node.left)
if k < left:
node = node.left
elif k == left:
return node.key
else:
k -= left + 1
node = node.right
return None
root = None
for key in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, key)
print(root.size) # 7
print(select(root, 0)) # 20
print(select(root, 3)) # 50
print(select(root, 6)) # 80Two details matter here.
updateis a separate function. Every operation that changes the tree's shape calls it, so the formula for the field lives in one place.updateruns after the recursive call returns. When it runs on a node, both child fields are already correct, so the node's field can be computed from them.
The diagram shows the tree built by this code. The number in parentheses is each node's size.
To see why select is fast, trace select(root, 3). At the root, the left subtree has size 3, and k is 3, so the root is the answer. Each step uses one stored number to discard a whole subtree, so the work is proportional to the height.
When a field can be maintained cheaply
Not every useful quantity makes a good augmentation. A field is practical when it meets one condition: you can compute it for a node in O(1) time from the node's own data and the fields of its two children. Call this the local-recompute rule.
When a field follows the rule, an insertion changes at most the fields of nodes on the path from the root to the new node. The other nodes' subtrees are unchanged, so their fields stay valid. Updating the path costs O(1) per node, so the total cost is O(h), the same as the insertion itself.
| Field | Local formula | Good augmentation? |
|---|---|---|
| Subtree size | 1 + left size + right size | Yes |
| Subtree sum of values | own value + left sum + right sum | Yes |
| Maximum of a value in the subtree | max(own value, left max, right max) | Yes |
| Depth of the node | parent's depth + 1 | No |
| Rank of the node in the whole tree | depends on nodes outside the subtree | No |
The last two rows break the rule because they depend on information above or beside the node. Inserting one key can change the depth of every node in a subtree, so maintaining that field would cost O(n). The first three depend only on what is below.
Failure modes to watch for
Augmented fields cause a few predictable bugs.
- Forgetting an update path. If one operation changes the tree without calling
updateon the affected nodes, stored fields become stale. Queries then return wrong answers without any error. The tree still looks like a valid BST, so ordinary tests of search may pass. - Updating in the wrong order. Fields must be recomputed from the bottom up. If you update a node before its changed child, you read the child's old value.
- Ignoring structural changes. Deletion and rotations also change which nodes are in which subtree. Both can invalidate fields. Later chapters cover them, and the rule is the same: after any change, recompute the fields of the changed nodes, lowest first.
- Storing derived data you could compute. Each field adds memory per node and adds work to every update. Add one only when a query needs it.
A cheap safeguard is a checker that walks the whole tree, recomputes every field from scratch, and compares it with the stored value. Run it in tests after sequences of operations.
def check_sizes(node):
# Returns the true size of the subtree, raising if any stored size is wrong.
if node is None:
return 0
expected = 1 + check_sizes(node.left) + check_sizes(node.right)
if node.size != expected:
raise AssertionError(f"node {node.key}: stored {node.size}, expected {expected}")
return expected
print(check_sizes(root)) # 7What stays the same
Augmentation does not change the tree's ordering rules or its shape. Search by key, insertion position, and traversal order are the same as in a plain BST. What changes is the work done on the way back up from each modification, plus the new queries the field makes possible. This is why the technique composes well with balanced trees: a rebalancing step only needs to call update on the nodes it moves.
Exercise
In the size-augmented tree, you call insert(root, 45) on the seven-key tree from this chapter. Which nodes have their size changed, and what are the new values?
Show answer
Key 45 is greater than 40, so it goes to the right of 40. The path from the root is 50, 30, 40, and the new node. The sizes on that path increase by one: 50 goes from 7 to 8, 30 goes from 3 to 4, and 40 goes from 1 to 2. The new node 45 has size 1. Nodes 20, 70, 60, and 80 are off the path and keep their sizes.
Exercise
A teammate proposes storing depth in each node so that depth queries are O(1). Using the local-recompute rule, explain why this field is a poor augmentation.
Show answer
A node's depth is computed from its parent, not from its own data and its children's fields, so it violates the rule. Changing the shape of the tree near the root, for example by a rotation, can change the depth of every node in a whole subtree. Keeping the field correct would then cost O(n) per modification instead of O(h).