Sub topic 13
Range queries and ordered iteration
This chapter assumes you can write the BST search, insert, and in-order traversal from earlier chapters, and that you know recursion, Python generators, and introductory Big-O. A range query returns every key between a lower and an upper bound. A BST can answer it without scanning the whole tree.
Why a range query is not just a filtered traversal
The simplest approach is to run an in-order traversal and keep keys where lo <= key <= hi. That is correct, but it visits all n nodes.
The ordering property lets you skip whole subtrees:
- If
node.key <= lo, everything in the left subtree is smaller thannode.key, so none of it can be at leastlo. Skip the left subtree. - If
node.key >= hi, everything in the right subtree is larger, so none of it can be at mosthi. Skip the right subtree.
A pruned range query
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def range_query(node, lo, hi):
if node is None:
return
if lo < node.key:
yield from range_query(node.left, lo, hi)
if lo <= node.key <= hi:
yield node.key
if node.key < hi:
yield from range_query(node.right, lo, hi)
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(list(range_query(root, 35, 65))) # [40, 50, 60]The function is an in-order traversal with two guards, so results come out sorted. The guards use strict comparisons (lo < node.key, node.key < hi) because a left subtree can only help when lo is below the node's key, and a right subtree only when hi is above it.
Cost
The query follows at most two root-to-leaf paths, the ones toward lo and toward hi. Every other visited node lies inside the range and is reported. The cost is O(h + k), where h is the tree height and k is the number of keys returned. On a balanced tree that is O(log n + k). On a degenerate tree h can be n, so the bound becomes O(n).
Ordered iteration without recursion
Generators built with yield from are easy to read, but each key passes up through every level of recursion. A deep tree can also hit Python's recursion limit. An explicit stack gives a lazy iterator that holds only the path to the current node. It can also start at any lower bound.
def iterate_from(root, lo):
stack = []
node = root
while node is not None:
if node.key >= lo:
stack.append(node)
node = node.left
else:
node = node.right
while stack:
node = stack.pop()
yield node.key
node = node.right
while node is not None:
stack.append(node)
node = node.left
print(list(iterate_from(root, 45))) # [50, 60, 70, 80]The first loop descends toward lo and pushes only the nodes whose keys are at least lo. These are the nodes that could still be output, with the smallest on top. After each pop, the loop pushes the left spine of the right subtree. Those keys are all larger than the key just yielded, so none needs a bound check.
Because this is a generator, the caller can stop early. Taking the first 3 keys at or above lo costs O(h + 3). This is the basis of "next k items after X" queries in ordered maps.
Common errors
- Using
<=where the code needs<in the pruning tests. This does not change correctness, but it makes you visit subtrees that cannot contain results. - Collecting results in a list and then filtering. This loses the O(h + k) bound.
- Forgetting that inclusive and exclusive bounds change only the middle test,
lo <= node.key <= hi, not the pruning tests.
Exercise
In the tree built from [50, 30, 70, 20, 40, 60, 80], which nodes does range_query(root, 55, 65) visit, and what does it return?
Show answer
It visits 50, 70, and 60. At 50, lo (55) is not below 50, so the left subtree is skipped, and 50 is outside the range. 50 < 65, so it goes right to 70. At 70, 55 < 70, so it goes left to 60. 70 is outside the range and 70 < 65 is false, so 80 is skipped. At 60, both of its children are None, and 60 is in range. The result is [60].