19. Quadtrees & K-D Trees
Recursively subdivide space to find nearby points without checking every one
You have a million points on a map and you need to find the ten closest to a given location. The brute-force approach checks every single point -- that's O(n) per query. If you're running this in a game loop at 60 fps or processing millions of GPS coordinates, that linear scan becomes a bottleneck fast.
The insight is old and elegant: organize points by where they are in space, so you can skip entire regions that can't possibly contain the answer. Quadtrees and K-D trees are two of the most widely used data structures for exactly this. Both recursively subdivide space, but they carve it up in fundamentally different ways.
The Problem: Spatial Queries Are Expensive
Two operations come up constantly in spatial computing:
| Query type | Question | Brute force |
|---|---|---|
| Range query | Which points lie inside this rectangle? | Check all n points: O(n) |
| Nearest neighbor | Which point is closest to this location? | Check all n points: O(n) |
With a spatial tree, both queries run in O(log n) on average, because at each level of the tree you eliminate a large fraction of the points without even looking at them.
Quadtrees: Divide Space into Four
A quadtree starts with a single rectangle that contains all points (the root). When a region contains more points than its capacity (typically 1--4), it splits into four equal quadrants: northwest, northeast, southwest, southeast. Each quadrant is itself a quadtree node that can split further.
Space-Driven Splits
Quadtrees always split at the midpoint of the region, regardless of where the points actually are. The partition is driven by the space, not by the data. This means some quadrants may be empty while others are deeply subdivided.
Building a Quadtree
-
Start with the bounding box
Create a root node whose boundary encloses all points. Set a capacity (say, 1 point per leaf).
-
Insert points one by one
For each point, walk down the tree to find the leaf whose boundary contains it. If the leaf has room, store the point there.
-
Subdivide when full
When a leaf exceeds its capacity, split it into four children (NW, NE, SW, SE) by cutting at the horizontal and vertical midpoints. Redistribute the existing points into the appropriate children.
-
Repeat recursively
The new children may immediately overflow if multiple points land in the same quadrant. Keep subdividing until every leaf is within capacity.
Worked Example: Inserting 8 Points
Points in a 100 x 100 region (capacity = 1)
Points: A(25,75) B(60,80) C(10,30) D(70,20)
E(55,55) F(80,70) G(40,10) H(90,40)
Step 1: Insert A(25,75) -- root has room [1 point, no split]
Step 2: Insert B(60,80) -- root is full, split!
Root splits into:
NW (0-50, 50-100) <- A goes here
NE (50-100, 50-100) <- B goes here
SW (0-50, 0-50)
SE (50-100, 0-50)
Step 3: Insert C(10,30) -> SW [no split needed]
Step 4: Insert D(70,20) -> SE [no split needed]
Step 5: Insert E(55,55) -> NE is full, split!
NE splits into:
NE-NW (50-75, 75-100) <- B goes here
NE-NE (75-100, 75-100)
NE-SW (50-75, 50-75) <- E goes here
NE-SE (75-100, 50-75)
Step 6: Insert F(80,70) -> NE-SE [no split needed]
Step 7: Insert G(40,10) -> SW is full, split!
SW splits into:
SW-NW (0-25, 25-50) <- C goes here
SW-NE (25-50, 25-50)
SW-SW (0-25, 0-50)
SW-SE (25-50, 0-25) <- G goes here
Step 8: Insert H(90,40) -> SE is full, split!
SE splits into:
SE-NW (50-75, 25-50)
SE-NE (75-100, 25-50) <- H goes here
SE-SW (50-75, 0-25) <- D goes here
SE-SE (75-100, 0-25)
Final tree depth: 3
Notice how the splits happen at fixed midpoints (50, then 25 and 75) regardless of point positions. Clusters of points cause deeper subdivision in their neighborhood while sparse areas stay shallow.
Range Query: Pruning Entire Subtrees
To find all points inside a query rectangle, start at the root and apply a simple rule at each node:
The Pruning Rule
If a node's boundary does not intersect the query rectangle, skip it and all its children. This single check eliminates entire subtrees -- potentially millions of points -- in one comparison.
Range query: find points in (60,50) to (100,90)
Start at root:
Check NW (0-50, 50-100) -- no overlap with query -> PRUNE
Check NE (50-100, 50-100) -- overlaps -> descend
Check NE-NW (50-75, 75-100) -- overlaps -> check B(60,80) inside
Check NE-NE (75-100, 75-100) -- overlaps -> empty
Check NE-SW (50-75, 50-75) -- overlaps -> check E(55,55) inside
Check NE-SE (75-100, 50-75) -- overlaps -> check F(80,70) inside
Check SW (0-50, 0-50) -- no overlap with query -> PRUNE
Check SE (50-100, 0-50) -- no overlap with query -> PRUNE
Result: {B, E, F}
Nodes visited: 8 out of 17 total (pruned 9 nodes)
The query only visited the nodes that could contain results. The entire left half and bottom-right of the tree were pruned in a single check each.
Nearest-Neighbor Search
Finding the single closest point is trickier than a range query, but the same pruning idea applies:
-
Start with the best guess
Descend to the leaf containing the query point. The point stored there (if any) becomes the initial "best candidate" with distance d.
-
Backtrack and prune
For each sibling node, check: is the closest possible point in that quadrant closer than d? If not, skip the entire subtree. If so, recurse into it.
-
Update the best
Whenever you find a closer point, update d. As d shrinks, more and more quadrants get pruned.
In practice, the first guess is usually very good, so most of the tree gets pruned immediately. Average case is O(log n).
K-D Trees: Alternate the Splitting Dimension
A K-D tree (k-dimensional tree) takes a completely different approach. Instead of splitting into four quadrants, each node makes a single binary split along one axis. The axis alternates at each level:
| Depth | Split axis | Rule |
|---|---|---|
| 0 | x | Points with x < median go left, others go right |
| 1 | y | Points with y < median go left, others go right |
| 2 | x | Split on x again |
| 3 | y | Split on y again |
Data-Driven Splits
Unlike quadtrees, K-D trees split at the median point along the chosen axis. This means the tree is always balanced (each split puts half the points on each side), regardless of how the data is distributed. The partition is driven by the data, not by the space.
Building a K-D Tree
-
Choose the splitting axis
At depth 0, split on x. At depth 1, split on y. Alternate with
axis = depth % k(where k is the number of dimensions -- 2 for 2D). -
Find the median
Sort the current points along the splitting axis and pick the median. This point becomes the node.
-
Recurse on each half
Points before the median go to the left subtree; points after go to the right. Recurse with depth + 1 until each subtree has zero points.
Worked Example: Building a K-D Tree from 7 Points
Points: (30,40) (5,25) (10,12) (70,70) (50,30) (35,45) (60,80)
Depth 0 -- split on X:
Sort by x: (5,25) (10,12) (30,40) (35,45) (50,30) (60,80) (70,70)
Median: (35,45)
Left: {(5,25) (10,12) (30,40)}
Right: {(50,30) (60,80) (70,70)}
Depth 1, Left -- split on Y:
Sort by y: (10,12) (5,25) (30,40)
Median: (5,25)
Left: {(10,12)}
Right: {(30,40)}
Depth 1, Right -- split on Y:
Sort by y: (50,30) (70,70) (60,80)
Median: (70,70)
Left: {(50,30)}
Right: {(60,80)}
Final tree:
(35,45) x
/
(5,25) y (70,70) y
/ \ /
(10,12) (30,40) (50,30) (60,80)
The tree is perfectly balanced: every leaf is at the same depth. This happens because we always choose the median as the splitter.
K-D Tree Search
Searching a K-D tree is like a binary search that alternates dimensions:
Nearest neighbor query for point (32, 38)
Start at root (35,45), split on x:
32 < 35 -> go left, but remember right subtree
At (5,25), split on y:
38 > 25 -> go right
At (30,40) -- leaf node
Distance to (32,38): sqrt(4+4) = 2.83
Best so far: (30,40), d = 2.83
Backtrack to (5,25):
Distance to (32,38): sqrt(729+169) = 29.97 -- worse
Could left child (10,12) be closer?
Closest possible y-distance: |38-25| = 13 > 2.83 -> PRUNE left
Backtrack to root (35,45):
Distance to (32,38): sqrt(9+49) = 7.62 -- worse
Could right subtree be closer?
Closest possible x-distance: |32-35| = 3 > 2.83 -> PRUNE right
Result: (30,40), distance = 2.83
Nodes visited: 4 out of 7
Quadtrees vs. K-D Trees
| Property | Quadtree | K-D Tree |
|---|---|---|
| Split strategy | Space-driven (midpoints) | Data-driven (medians) |
| Branching factor | 4 children per node | 2 children per node |
| Balance | Unbalanced (data-dependent depth) | Balanced when built with medians |
| Dynamic inserts | Easy -- just subdivide | Hard -- can unbalance the tree |
| Build time | O(n log n) average | O(n log n) with median-of-medians |
| Query time | O(log n) average, O(n) worst | O(log n) average, O(n) worst |
| Best for | Dynamic data, uniform distributions | Static data, any distribution |
In practice, quadtrees shine when points are inserted and deleted frequently (like objects moving in a game) because you don't need to rebuild the tree. K-D trees shine when you have a fixed dataset and want guaranteed balance for fast queries.
Higher Dimensions
Both structures generalize beyond 2D, but in very different ways:
| Dimensions | Quadtree family | K-D tree |
|---|---|---|
| 2D | Quadtree (4 children) | Split x, y, x, y... |
| 3D | Octree (8 children) | Split x, y, z, x, y, z... |
| kD | 2k-tree (exponential children) | Cycle through k axes |
The Curse of Dimensionality
In high dimensions, spatial trees lose their advantage. When k is large, the "nearby" region becomes a tiny fraction of the space, and the pruning rule eliminates fewer and fewer subtrees. Beyond roughly 20 dimensions, a linear scan often beats a K-D tree. For high-dimensional nearest neighbors, techniques like locality-sensitive hashing (LSH) or approximate methods are preferred.
Complexity Summary
| Operation | Average | Worst case |
|---|---|---|
| Build | O(n log n) | O(n log n) for K-D; O(n^2) for quadtree with degenerate input |
| Insert | O(log n) | O(n) if all points cluster in one region |
| Range query | O(log n + k) where k = results | O(n) if every quadrant overlaps the query |
| Nearest neighbor | O(log n) | O(n) with adversarial distributions |
| Space | O(n) for K-D tree; O(n) to O(n*d) for quadtree (d = max depth) |
The worst case for both structures is degenerate input -- for example, all points on a single line force a quadtree into very deep subdivision. Randomized or well-distributed inputs give the average-case performance.
Where They're Used
| Application | How spatial trees help |
|---|---|
| Collision detection (games) | Quadtrees partition the game world so each object only checks neighbors in its region, not every object |
| Geographic Information Systems | Index millions of map features (roads, buildings) for fast spatial lookups and rendering |
| Image compression | Quadtree decomposition: uniform regions become single nodes, detail is preserved where needed |
| Barnes-Hut simulation | Group distant bodies into single "super-bodies" to approximate gravitational force -- reduces n-body from O(n^2) to O(n log n) |
| Ray tracing | K-D trees partition the scene so rays only test intersection with nearby geometry |
| Machine learning (k-NN) | K-D trees accelerate k-nearest-neighbor classification for low-dimensional feature spaces |
Key Takeaways
- Quadtrees and K-D trees both recursively subdivide space to make spatial queries sublinear
- Quadtrees split space at midpoints (space-driven); K-D trees split at medians (data-driven)
- Both achieve O(log n) average for insert, range query, and nearest-neighbor search
- Quadtrees have 4 children per node and handle dynamic inserts well; K-D trees are binary and stay balanced
- The pruning rule -- skip regions that can't contain the answer -- is what makes these structures fast
- Quadtrees become octrees in 3D; K-D trees generalize to any dimension but degrade in high dimensions
- They power collision detection, GIS, image compression, n-body simulation, ray tracing, and more
Try It Yourself -- Quadtree Visualizer
Click on the canvas to place points. Watch the quadtree subdivide as regions fill up. Then drag a rectangle to perform a range query and see which quadrants get pruned.
Click to add points. Click and drag to draw a range query rectangle. Green = found. Red outline = pruned regions.
Quadtrees and K-D trees are your first encounter with a powerful idea: hierarchical spatial indexing. By organizing data according to where it lives in space, you can answer "what's nearby?" without looking at everything. This same principle extends to R-trees for rectangles, ball trees for high-dimensional data, and bounding volume hierarchies for 3D rendering -- all descendants of the simple idea that you can prune what you can't possibly need.