Sub topic 5
Range search in a k-d tree
This chapter assumes you can read the build function from the previous chapter, and that you know recursion and axis-aligned rectangles. A range search returns every point inside a query box. It does this without testing all n points.
The query
A box is given by two corners, lo and hi. A point p is inside when lo[i] <= p[i] <= hi[i] holds on every axis i. The boundaries are included.
Each k-d tree node splits space at node.point[axis]. Points in the left subtree have a value on that axis that is less than or equal to the split value. Points in the right subtree have a value greater than or equal to it. This gives two pruning rules:
- If
lo[axis]is greater than the split value, the box lies entirely on the right, so skip the left subtree. - If
hi[axis]is less than the split value, the box lies entirely on the left, so skip the right subtree.
If the box straddles the split, visit both children.
Implementation
This code includes the node and build code, so it runs as shown.
class Node:
def __init__(self, point, axis, left, right):
self.point = point
self.axis = axis
self.left = left
self.right = right
def build(points, depth=0):
if not points:
return None
axis = depth % len(points[0])
points = sorted(points, key=lambda p: p[axis])
mid = len(points) // 2
return Node(points[mid], axis,
build(points[:mid], depth + 1),
build(points[mid + 1:], depth + 1))
def in_box(p, lo, hi):
return all(l <= x <= h for x, l, h in zip(p, lo, hi))
def range_search(node, lo, hi, found=None):
if found is None:
found = []
if node is None:
return found
if in_box(node.point, lo, hi):
found.append(node.point)
split = node.point[node.axis]
if lo[node.axis] <= split:
range_search(node.left, lo, hi, found)
if hi[node.axis] >= split:
range_search(node.right, lo, hi, found)
return found
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
tree = build(points)
print(sorted(range_search(tree, (4, 1), (8, 4))))
# [(5, 4), (7, 2), (8, 1)]The root is (7, 2) and it splits on x. The box spans x from 4 to 8, so it straddles 7 and both sides are searched. In the right subtree, (9, 6) splits on y at 6. The box tops out at y = 4, so the search skips that node's right child.
The comparisons use <= and >=, not strict inequalities. A point equal to the split value can sit in either subtree, so a strict test would miss it when duplicates exist.
Cost
The cost has two parts. The first is the nodes the search must visit to find the boundary of the box. The second is the m points that it reports.
| Case | Time |
|---|---|
| Balanced tree, k dimensions | O(n^(1 - 1/k) + m) |
| Two dimensions | O(√n + m) |
| Box covers everything | O(n) |
A small box that matches few points is fast. A box that covers most of the data must return most of the data, so no index can beat O(m).
Common errors
- Writing
lo[0]orhi[0]instead of usingnode.axis. The axis changes with depth. - Testing only the node's split coordinate, not the whole point, before reporting it.
- Sharing a default list across calls. The code above uses
found=Noneto avoid this.
Exercise
A tree node splits on y at value 5. The query box has lo = (0, 6) and hi = (10, 9). Which subtrees does range_search visit, and is the node's own point reported if it is (3, 5)?
Show answer
Only the right subtree is visited. The left test lo[1] <= 5 is 6 <= 5, which is false, so the left subtree is skipped. The right test hi[1] >= 5 is 9 >= 5, which is true. The point (3, 5) is not reported because its y value 5 is below lo[1] = 6.