Sub topic 2
Splitting space and pruning branches
This chapter assumes you know recursion, Big-O notation, and basic Python. It also assumes you can work with coordinates, Euclidean distance, and axis-aligned rectangles. It covers the idea behind both k-d trees and quadtrees: divide space into regions, then skip regions that cannot hold an answer.
Why a scan is not enough
A range query asks for every point inside a rectangle. A nearest-neighbor query asks for the closest point to a target. A linear scan answers either one by checking all n points, which costs O(n) per query. That is fine for one query. It is too slow for a map that answers thousands of queries per second over millions of points.
The fix is to pay once to organize the points, so that each later query touches only a small part of them.
Splitting space
Space partitioning divides the coordinate space into non-overlapping regions and records which points fall in each region. You can apply the split again inside each region, which gives a tree. Each node represents a region, and its children represent the sub-regions.
The two structures in this tutorial differ in how they choose the splits:
| Structure | Split rule | Children per node |
|---|---|---|
| k-d tree | One axis at a time, at the median point | 2 |
| Quadtree | Both axes at once, at the cell's center | 4 |
Pruning
Pruning means skipping a whole subtree because its region cannot contain anything useful. Every query rests on one question asked at each node: could any point in this region matter?
- For a range query, the answer is no if the region does not overlap the query rectangle.
- For a nearest-neighbor query, the answer is no if the closest possible point in the region is farther away than the best match found so far.
One rejected node removes every point beneath it. This is why the cost depends on the data's layout and not only on n.
A one-level example
Before building trees, you can see pruning with a single round of splitting. The code below puts 1000 random points into four cells and then runs a range query that skips cells whose box misses the rectangle.
import random
random.seed(1)
points = [(random.random() * 100, random.random() * 100) for _ in range(1000)]
# Split the square [0, 100) x [0, 100) into four cells at x = 50 and y = 50.
cells = {}
for p in points:
key = (p[0] >= 50, p[1] >= 50)
cells.setdefault(key, []).append(p)
def cell_box(key):
x_hi, y_hi = key
return (50 if x_hi else 0, 50 if y_hi else 0,
100 if x_hi else 50, 100 if y_hi else 50)
def range_query(xmin, ymin, xmax, ymax):
found, checked = [], 0
for key, members in cells.items():
bx0, by0, bx1, by1 = cell_box(key)
if xmax < bx0 or xmin >= bx1 or ymax < by0 or ymin >= by1:
continue # prune: the cell's box misses the query
for p in members:
checked += 1
if xmin <= p[0] <= xmax and ymin <= p[1] <= ymax:
found.append(p)
return found, checked
found, checked = range_query(0, 0, 20, 20)
print(len(found), "matches,", checked, "points examined out of", len(points))The query rectangle lies entirely in the lower-left cell, so three cells are skipped without looking at any of their points. The program examines roughly a quarter of the data. A tree repeats this trick at every level, so the savings compound.
Where pruning fails
Pruning pays off only when the query is small compared with the regions. Two situations remove the benefit:
- A query rectangle that covers most of the space overlaps most regions, so nothing is pruned.
- Poorly balanced splits, such as many points crowded into one region, leave one subtree holding most of the data. Pruning the other subtrees then saves little.
The next chapters show how k-d trees avoid the second problem by splitting at the median, and how quadtrees handle it by subdividing only where points cluster.
Exercise
In the example above, the query rectangle is changed to (0, 0, 60, 20). How many of the four cells does the query examine, and why can the other cells still be pruned?
Show answer
It examines two cells, the lower-left and lower-right. The rectangle spans x from 0 to 60, so it overlaps both cells with y below 50. It reaches only y = 20, so it misses the two upper cells (ymax = 20 is less than their lower edge at y = 50), and both are pruned.