Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Don’t search where it can’t be
To find the nearest gas station you don’t measure the distance to every station in the country. You look in your own neighbourhood first, and only check the next district over if it could possibly have something closer. A k-d tree organises points into nested boxes (split left/right, then up/down, and so on). A ball tree organises them into nested spheres. Searching then visits only the few boxes or balls near the query, which is often thousands of times faster than checking everything.
Real-time robotics runs nearest-neighbour queries constantly: matching lidar points in ICP scan alignment, querying maps for obstacles, looking up features for place recognition. k-d trees (as in PCL and nanoflann) make these feasible at sensor rates. Knowing when trees stop helping, namely in high dimensions, tells you when to switch to approximate indexes.
- 1. A k-d tree splits space with…
- 2. Tree search saves time by…
- 3. In the demo, how much of the data is checked in 2-D?
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.Building and searching by hand
Build (leaf size 1) on x = 1, 3, 5, 9 (1-D):
- the median split is at 5, giving a left half [1, 3] and a right half [5, 9];
- the left half splits at 3 into [1] | [3]; the right half splits at 9 into [5] | [9].
Search for q = 4.2:
- Descend: 4.2 is below 5, so go left; 4.2 ≥ 3, so reach leaf [3]. Best = |4.2 − 3| = 1.2.
- Backtrack to the node “split at 3”. The other side [1] is |4.2 − 3| = 1.2 from the plane, which is not less than 1.2, so prune it (no distance computed).
- Backtrack to the root “split at 5”. The plane is |4.2 − 5| = 0.8 away, below 1.2, so the right side might hold something closer. Visit it. Point 5 is 0.8 away: the new best.
- Its sibling 9 is in a cell whose plane is |4.2 − 9| = 4.8 away, so prune it.
Result: nearest = 5, after 2 distance computations instead of 4.
Ball-tree pruning. For a ball with centre c and radius ρ, every point inside is at least ‖q − c‖ − ρ from q. If that lower bound already exceeds the best distance, skip the whole ball.
The steps in plain English:
- Build: pick the axis of widest spread, split at the median, and recurse until leaves have at most leaf_size points.
- Search: go down to the leaf containing the query and record the best distance.
- Back up: at each split, visit the other side only if the splitting plane (or ball) is closer than the current best.
- For k neighbours, keep the k best in a heap and use the k-th distance for pruning.
- Use brute force anyway if dimension is high and data are unstructured.
- 1. In the example, why was the {1} cell pruned?
- 2. Lower bound for points in a ball with centre 5 units away and radius 2?
- 3. For k neighbours, pruning uses…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.The structures
k-d tree (Bentley, 1975):
- each internal node stores a split axis and value; children cover the half-spaces;
- build: O(n log n) (with median selection);
- search for random queries in fixed low d: about O(log n) node visits;
- worst case: O(n).
Ball tree (Omohundro, 1989; Uhlmann, 1991):
- each node stores a centre and covering radius;
- it works with any metric that satisfies the triangle inequality, not only Euclidean;
- it is often better than a k-d tree in moderate dimensions or for clustered data, because balls adapt to the data’s shape (exercise 2).
Leaf size trades tree overhead against brute-force work in the leaves. A typical value is 10–40.
k-NN and radius queries use the same pruning, with a k-element heap or a fixed radius.
from sklearn.neighbors import KDTree, BallTree, NearestNeighbors
tree = KDTree(X, leaf_size=30); dist, ind = tree.query(Q, k=5)
BallTree(X, metric="haversine") # great-circle distances on lat/long
NearestNeighbors(n_neighbors=5, algorithm="auto").fit(X) # picks brute / kd / ball heuristically
from scipy.spatial import cKDTree # fast C++ k-d treeUse them when dimensions are low to moderate (up to about 10–20) or the intrinsic dimension is low, there are many queries, and exact answers are needed. Use approximate methods (HNSW, IVF, LSH) for high-dimensional embeddings at scale.
- 1. Ball trees work with any metric that satisfies…
- 2. k-d tree construction costs about…
- 3. scipy's fast k-d tree class is…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Why trees fail in high dimensions
The ball around the query. Pruning works when the ball of radius (best distance) around the query intersects few cells. In d dimensions:
- the nearest-neighbour distance grows like n^(−1/d), large unless n is exponential in d;
- a ball of that radius crosses splitting planes in most coordinates.
So almost every cell must be checked. Friedman, Bentley and Finkel (1977) showed that the expected search cost grows like about 2^d. Trees are effective only when n ≫ 2^d.
Intrinsic dimension rescues them. What matters is the dimension of the data manifold, not the ambient space. Data near a 2-D plane in 32-D behave like 2-D data for a ball tree. This is why trees still work for many real datasets (exercise 2: 4% of brute-force work instead of 100%).
Approximate search:
- (1 + ε)-approximate k-d search prunes more aggressively;
- locality-sensitive hashing (Indyk and Motwani, 1998) gives sublinear time with guarantees;
- graph-based indexes (HNSW, Malkov and Yashunin, 2018) dominate practical benchmarks for embedding search;
- product quantisation and IVF (FAISS) compress vectors for billion-scale search.
Interview questions.
- When would you not use a k-d tree? With high-dimensional unstructured data (more than about 20 dimensions), or few queries per build. Use brute force (BLAS-fast) or approximate indexes instead.
- Why can a ball tree beat a k-d tree? Its nodes fit the data’s shape, including clusters and low-dimensional structure, instead of axis-aligned boxes. It also supports any metric.
- 1. Tree search cost grows roughly like…
- 2. What rescues trees on high-dimensional real data?
- 3. HNSW is…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.How much work do trees save?
History.
- Bentley (1975) introduced the k-d tree.
- Friedman, Bentley and Finkel (1977) analysed logarithmic expected search and its dimensional limits.
- Omohundro (1989) and Uhlmann (1991) introduced ball and metric trees.
- Arya et al. (1998) developed approximate k-d search (ANN).
- Indyk and Motwani (1998) introduced locality-sensitive hashing.
- Muja and Lowe’s FLANN (2009) was adopted in OpenCV and PCL.
- HNSW (2016–2018) and FAISS (2017) dominate large-scale vector search today.
Exercise 1. 2000 uniform points in 2-D, 100 queries. Both trees always return the exact nearest neighbour, evaluating about 14 (k-d) and 15 (ball) distances per query instead of 2000.
Exercise 2: dimension. Setup: 4000 points, 50 queries from the same distribution. The table shows the fraction of brute-force distance evaluations.
| Data | k-d tree | Ball tree |
|---|---|---|
| Uniform, d = 2 | 0.003 | 0.004 |
| Uniform, d = 4 | 0.014 | 0.014 |
| Uniform, d = 8 | 0.140 | 0.085 |
| Uniform, d = 16 | 0.997 | 0.934 |
| Uniform, d = 32 | 1.000 | 1.000 |
| Near a 2-D plane in 32-D | 0.082 | 0.045 |
- In 2–4 dimensions, trees cut the work 70–300-fold.
- By d = 16 with 4000 points, they do essentially brute force, plus overhead. n is far below 2^16.
- Ambient dimension is not the problem; intrinsic dimension is. Data on a 2-D plane embedded in 32-D are searched at 4–8% of brute-force cost. The ball tree adapts better, because its spheres follow the plane while the k-d tree’s axis-aligned boxes do not.
Search structures in AI, robotics and aerospace
- Point-cloud registration (ICP): k-d tree correspondences between lidar scans.
- Motion planning: nearest-node queries in RRT and PRM planners.
- Map queries: obstacles within range, nearest landmark for localisation.
- Vector databases: approximate indexes for embedding retrieval in AI systems.
References
- J. L. Bentley (1975). “Multidimensional binary search trees used for associative searching.” Communications of the ACM 18(9).
- J. H. Friedman, J. L. Bentley, R. A. Finkel (1977). “An algorithm for finding best matches in logarithmic expected time.” ACM Transactions on Mathematical Software 3(3).
- S. M. Omohundro (1989). “Five balltree construction algorithms.” ICSI Technical Report TR-89-063.
- P. Indyk, R. Motwani (1998). “Approximate nearest neighbors: towards removing the curse of dimensionality.” STOC.
- Y. A. Malkov, D. A. Yashunin (2018). “Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs.” IEEE TPAMI 42(4).