Sub topic 11
Choosing between k-d trees, quadtrees and library indexes
This chapter assumes you have read the earlier chapters on k-d tree and quadtree construction, range search and nearest-neighbor search. You should also know the complexity results from the previous chapter. Here you will turn those results into a decision.
What to compare
Both structures prune space, so the choice depends on your data and your queries. Four questions settle most cases:
- How many dimensions does the data have?
- Does the point set change after you build the index?
- Are the points evenly spread or clustered?
- Which query matters most: rectangular range queries or nearest neighbor?
Side-by-side comparison
| Property | K-d tree | Point quadtree |
|---|---|---|
| Dimensions | Any k, works well up to roughly 10-20 | Fixed at 2 (octree for 3) |
| Build | Median split gives a balanced tree in O(n log n) | Insert one by one, no global rebalancing |
| Updates | Insertion is easy, deletion is awkward, rebuild after many changes | Insertion and deletion are cheap and local |
| Clustered data | Median split adapts to the density | Deep subtrees form around clusters, so `max_depth` is needed |
| Nearest neighbor | Natural, as in the earlier `nearest` function | Possible, but needs extra bookkeeping |
| Range query | Good | Very good for 2D rectangles |
The median split is the main reason k-d trees handle clustering better. A quadtree splits at the center of a cell, whatever the data looks like. If a thousand points sit in a tiny corner, the quadtree subdivides repeatedly until max_depth stops it.
A decision path
When to use a library
Your hand-written trees are good for learning and for small, special cases such as a game with a few thousand moving objects. For production work, prefer a tested library. Libraries are usually faster because they store points in contiguous arrays, avoid Python object overhead, and run the traversal in compiled code.
import numpy as np
from scipy.spatial import cKDTree
points = np.array([(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)])
tree = cKDTree(points)
dist, idx = tree.query((9, 2))
print(round(float(dist), 3), points[idx].tolist()) # 1.414 [8, 1]
near = tree.query_ball_point((9, 2), r=2.5)
print(sorted(near)) # [4, 5]This finds the same nearest point, (8, 1), as the hand-built tree. query_ball_point returns the indices of all points within a radius. It is a circular query, not the rectangular query from the quadtree chapter.
Common mistakes
- Using a k-d tree for 100-dimensional embeddings. Pruning rarely succeeds there, so queries approach a linear scan. Consider approximate nearest-neighbor libraries instead.
- Rebuilding a k-d tree after every insertion. Batch the changes, or rebuild only when the tree becomes unbalanced.
- Forgetting the bounds of a quadtree. Points outside the root square are rejected, as the
containscheck in our code shows. - Benchmarking on tiny inputs. For a few hundred points, a plain linear scan with NumPy can beat any tree.
Exercise
A mapping app stores 2 million 2D points that change constantly as vehicles move, and it mostly answers "which vehicles are inside this screen rectangle?" Which structure would you choose first, and why?
Show answer
A quadtree. The data is 2D, updates are frequent and cheap in a quadtree because insertion and deletion stay local, and rectangular range queries are its strength. If the vehicles cluster heavily in cities, set a sensible max_depth and check performance against a library index.