Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Spatial trees: k-d trees, quadtrees and octrees

ProblemOrganise points so that the nearest ones to a query, or all of those within a distance or a box, are found without examining every point
Devised byJon Bentley (1975), k-d trees; Raphael Finkel and Jon Bentley (1974), quadtrees; Donald Meagher (1980), octrees
AccuracyExact: the same 8 nearest neighbours as SciPy’s cKDTree for 200 of 200 queries, and the same counts within a radius (see the chapter overview)
CostBuild ; a nearest-neighbour query about for well-spread points in low dimensions, against for a scan
Read firstGeometric types: points, vectors, shapes and shared tables
APIKdTree (new, nearest, k_nearest, within_radius, range_query), RegionTree (new, with_limits, from_points, insert, remove, nearest, k_nearest, query_radius, query_box, depth), QuadTree, OctTree

Overview

Finding the point nearest to a query by checking every point costs . Repeated for queries, as in clustering, point-cloud registration, collision detection or interpolation of scattered data, that is . Spatial trees divide space hierarchically, so that whole regions can be ruled out at once because they are farther than the best point found so far. A k-d tree splits the points at the median along alternating axes, so its cells adapt to the points. A quadtree (in 2D) or octree (in 3D) splits space into equal quadrants or octants, so its cells are regular, and it accepts insertions and removals.

Where it is used

Spatial trees make “who is near me?” queries fast.

  • Nearest-neighbour search. The k-d tree under k-nearest-neighbour classifiers and clustering algorithms of the machine-learning chapters.
  • Computer graphics and games. Octrees and quadtrees cull what is not visible and accelerate collision queries.
  • GIS and robotics. Finding the nearest road, landmark or point of a laser scan; building occupancy maps of the world around a robot.
  • Scientific computing. Neighbour lists for molecular dynamics and N-body simulations.

History

Jon Bentley introduced the k-d tree as an undergraduate project at Stanford, published in 1975, and with Jerome Friedman and Raphael Finkel (1977) gave the logarithmic expected time of its nearest-neighbour search. Raphael Finkel and Bentley described the point quadtree in 1974, and region quadtrees became standard in image processing and geographic data through the 1980s, surveyed by Hanan Samet. Donald Meagher (1980) introduced the octree for solid modelling. Their limits in high dimensions, where every query visits most of the tree, led to approximate methods such as locality-sensitive hashing and graph-based search.

The idea

k-d trees

To build, find the median of the points along ; it becomes the root, with the points to its left and right as subtrees. Split those at their medians along , then again, and so on. The library stores the tree implicitly: a permutation of the point indices in which each subslice’s middle element is the node and its halves are the subtrees, arranged with a linear-time selection at each level.

To find the nearest neighbours of , descend first into the side of each split containing , keeping the best points so far in a max-heap. On the way back, the other side can hold a closer point only if the splitting line is nearer to than the current -th best distance, . Usually it is not, and half the tree is skipped. Radius and box queries prune the same way.

Figure 24.7. Spatial trees.

Quadtrees and octrees

A quadtree covers a box. Each leaf holds up to a fixed number of points (8 by default). When a leaf overflows, it splits into four equal quadrants (eight octants in 3D) and hands its points down. Dense regions therefore get small cells, as in the clustered example above, and empty regions stay as single large leaves. A depth limit stops coincident points from splitting forever. Searches visit the children of each cell nearest first and skip any cell whose box is farther from the query than the current -th best.

The library’s RegionTree is generic over the dimension; QuadTree and OctTree are its 2D and 3D forms. Each entry carries an id chosen by the caller, so the same tree can index moving objects by removing and reinserting them.

Table 24.4. Build and query times of k-d trees and quadtrees.

pointsk-d buildquadtree buildk-d queryquadtree querybrute force query
100078 µs57 µs0.24 µs0.27 µs1.2 µs
10000599 µs522 µs0.34 µs0.41 µs11.4 µs
1000006.5 ms5.9 ms0.68 µs0.51 µs112.2 µs
100000099.5 ms182.8 ms1.64 µs1.15 µs1118.6 µs

Figure 24.8. Query timing.

For uniformly spread points both trees answer a nearest-neighbour query in a few microseconds even among a million points, where a scan takes milliseconds. The k-d tree is a little faster for static data. The quadtree costs about the same to build and allows updates.

Algorithm

Building a k-d tree on a list of point indices. build(slice, depth):

  1. if the slice is empty, return;
  2. choose the axis depth mod D, cycling through the coordinates;
  3. rearrange the slice with a linear-time selection so that its middle element is the median along that axis, with the smaller points before it and the larger after;
  4. the middle element is the node; call build on the two halves with depth + 1.

The cost is , and the tree needs no storage beyond the permuted indices.

Searching a k-d tree for the nearest neighbours of . search(slice, depth):

  1. visit the node: compute its distance to , and if it is among the best so far, insert it into the max-heap of results (removing the worst when the heap is full);
  2. compare with the node along the splitting axis to find which half contains , and search that half first;
  3. search the other half only if the distance from to the splitting plane is less than the current -th best distance (or fewer than points have been found).

Inserting into a region tree (quadtree or octree): descend from the root, at each cell choosing the child whose box contains the point, until a leaf is reached; add the point to the leaf. If the leaf now holds more than its capacity and is above the depth limit, divide it into equal children and move its points into them.

Nearest neighbours in a region tree: as for the k-d tree, with the children of each cell visited in order of the distance from to their boxes, and a child skipped when that distance exceeds the current -th best.

Implementation

    fn search_k(&self, slice: &[usize], depth: usize, q: &[f64; D], k: usize, heap: &mut BinaryHeap<Candidate>) {
        if slice.is_empty() {
            return;
        }
        let axis = depth % D;
        let mid = slice.len() / 2;
        let node = slice[mid];
        let cand = Candidate { dist2: dist2(&self.points[node], q), index: node };
        if heap.len() < k {
            heap.push(cand);
        } else if heap.peek().is_some_and(|worst| cand < *worst) {
            heap.pop();
            heap.push(cand);
        }
        let diff = q[axis] - self.points[node][axis];
        let (near, far) = if diff < 0.0 { (&slice[..mid], &slice[mid + 1..]) } else { (&slice[mid + 1..], &slice[..mid]) };
        self.search_k(near, depth + 1, q, k, heap);
        // The far side can only help if the splitting plane is closer than the current k-th best.
        if heap.len() < k || heap.peek().is_some_and(|worst| diff * diff <= worst.dist2) {
            self.search_k(far, depth + 1, q, k, heap);
        }
    }
  • Both trees work in any dimension D and return (index or id, distance) pairs, nearest first, with ties broken by index.
  • Points with non-finite coordinates are not indexed; a region tree refuses points outside its box.

In practice

//! Nearest-neighbour and range queries with a k-d tree, a quadtree and an octree.

use lib_jsl_geometry::algorithms::{KdTree, OctTree, QuadTree};

fn main() {
    let cities = [[0.0, 0.0], [3.0, 4.0], [-2.0, 1.0], [5.0, -1.0], [1.0, 1.0], [-4.0, -3.0], [2.5, 2.0]];
    let tree = KdTree::new(&cities);
    println!("nearest to (2, 2): {:?}", tree.nearest([2.0, 2.0]));
    println!("3 nearest to (0, 0): {:?}", tree.k_nearest([0.0, 0.0], 3));
    let mut near = tree.within_radius([0.0, 0.0], 2.5);
    near.sort_unstable();
    println!("within 2.5 of the origin: {near:?}");
    let mut boxed = tree.range_query([0.0, 0.0], [3.0, 4.0]);
    boxed.sort_unstable();
    println!("in the box [0, 3] × [0, 4]: {boxed:?}");

    // A quadtree takes insertions and removals; ids are chosen by the caller.
    let mut quad = QuadTree::new([-5.0, -5.0], [5.0, 5.0]);
    for (id, &p) in cities.iter().enumerate() {
        quad.insert(100 + id, p);
    }
    quad.remove(104, cities[4]);
    println!("quadtree nearest to (2, 2) after removing id 104: {:?}", quad.nearest([2.0, 2.0]));

    let cloud: Vec<[f64; 3]> = (0..1000).map(|i| { let t = i as f64 * 0.01; [t.cos(), t.sin(), 0.1 * t] }).collect();
    let oct = OctTree::from_points(&cloud);
    println!("octree of a helix: {} points, depth {}, nearest to (1, 0, 5): {:?}", oct.len(), oct.depth(), oct.nearest([1.0, 0.0, 5.0]));
}
nearest to (2, 2): Some((6, 0.5))
3 nearest to (0, 0): [(0, 0.0), (4, 1.4142135623730951), (2, 2.23606797749979)]
within 2.5 of the origin: [0, 2, 4]
in the box [0, 3] × [0, 4]: [0, 1, 4, 6]
quadtree nearest to (2, 2) after removing id 104: Some((106, 0.5))
octree of a helix: 1000 points, depth 5, nearest to (1, 0, 5): Some((673, 4.34962905756289))

Strengths

  • Exact queries, fast in two and three dimensions.
  • A dynamic quadtree and octree with caller-chosen ids.

Weaknesses

  • The k-d tree is static: adding points means rebuilding it.
  • In high dimensions (say above 10–20) pruning stops working and queries approach a scan; there are no approximate methods.

Exercises

  1. Show that the k-d tree built by median splits has depth .
  2. Explain why the far side of a split need not be searched when , and why this test is conservative.
  3. Construct a point set on which a quadtree with capacity 1 reaches depth (or its depth limit).
  4. For points uniform in the unit cube in dimensions, estimate the fraction of cells a nearest-neighbour search must examine as grows.
  5. Use a k-d tree to find all pairs of points closer than in time, where is the number of pairs.
Hints and answers
  1. Median splits give two children of sizes at most ; the number of levels until every node has one point is .
  2. The nearest point on the far side of the splitting plane is at least away; if that is at least the current best distance , the far side cannot contain a closer point. The test is conservative because it compares to the distance to the plane, not to the nearest actual point in the far cell.
  3. Place points so that each split separates only one point from the rest: for example on a line, so each subdivision halves the region but leaves almost all points in one quadrant.
  4. As grows, the distance to the nearest neighbour approaches the typical inter-point distance, so the search ball intersects most cells; the fraction of cells examined tends to 1 and the tree degenerates to brute force.
  5. For each point query its -neighbourhood in the tree; each query costs and the total is .

Further reading

  • J. L. Bentley, “Multidimensional binary search trees used for associative searching”, Communications of the ACM 18 (1975) 509–517.
  • J. H. Friedman, J. L. Bentley and R. A. Finkel, “An algorithm for finding best matches in logarithmic expected time”, ACM Transactions on Mathematical Software 3 (1977) 209–226.
  • R. A. Finkel and J. L. Bentley, “Quad trees: a data structure for retrieval on composite keys”, Acta Informatica 4 (1974) 1–9.
  • H. Samet, Foundations of Multidimensional and Metric Data Structures, Morgan Kaufmann, 2006.