Lesson 7 · Advanced structures and algorithms

K-D Trees

A binary search tree for points with several coordinates: each level splits space on one axis, so a search can throw away whole regions instead of measuring every point.

K-D Trees concept diagramTwo regions split by a vertical line. On the left the best-distance circle around the query stays clear of the line, so the far side is pruned; on the right the circle crosses it, so the far side must be searched.the dashed circle has radius = distance from q to the best point found so farcircle stays on its own sidefar sideprunedsplit x = sgapbestqgap ≥ best → skip the far subtreecircle reaches across the linefar sidemust searchsplit x = sgapbestqgap < best → search it as well
1

One Axis per Level

  1. Stores – points with k coordinates, such as (x, y) for k = 2 or (x, y, z) for k = 3.
  2. Shape – a binary tree; every node holds one point and splits space into two half-spaces.
  3. Splitting rule – a node at depth d compares coordinate d mod k: x at the root, y below it, then x again.
  4. Left / right – points with a smaller value on that axis go left; equal or larger go right.
  5. Used for – nearest neighbour search, range search, and k-nearest-neighbour queries.

A k-d tree (short for k-dimensional tree) is a binary search tree for multi-dimensional points. An ordinary BST compares one key; this tree has k keys per point and compares them in turn, one axis per level. For 2-D points the root splits the plane with a vertical line, its children split their halves with horizontal lines, and so on.

Each node therefore owns a rectangular cell of space: the root owns everything, and every split cuts one cell into two. That geometry is what makes the tree useful. A query about a location only needs the cells near that location, so most of the tree is never touched.

  • k is the number of dimensions, not the number of children
  • One point per node; each node's split line is clipped to its own cell
  • Axes cycle with depth: x, y, x, y… for k = 2
  • It is a space-partitioning tree, like a quadtree but always binary
2

Building the Tree: Median Splits

  1. Choose the axis – axis = depth mod k.
  2. Sort or select – order the current points by that coordinate.
  3. Take the median – it becomes the node; its value on the axis is the split.
  4. Recurse – build the left subtree from the points before the median and the right subtree from those after it, at depth + 1.
  5. Stop – an empty point set returns an empty subtree.

Choosing the median on each axis puts half the remaining points on each side, so the tree is balanced with height ⌈log₂(n + 1)⌉. Sorting at every level costs O(n log² n) in total; a linear-time median selection or pre-sorting each axis once brings construction down to O(n log n).

The tree can also be built by inserting points one at a time, exactly like a BST: walk down comparing the current axis, and attach the point where the walk falls off. Insertion is O(height), but the shape now depends on the order of insertion — sorted input produces a tree as tall as a linked list.

There is no cheap rotation to rebalance it, because rotating changes which axis a node splits on. Trees that receive many inserts are usually rebuilt from scratch, or replaced by a structure designed for updates.

  • Even number of points: either middle point works; the code takes index n // 2
  • Equal values on the axis go right, so the median's equals end up in its right subtree
  • Some libraries split on the axis with the widest spread instead of cycling x, y, x
3

Nearest Neighbour Search

  1. Descend – go down the side of each split that the query point q falls on, as if inserting q.
  2. Update the best – at every node visited, measure the distance to q and keep the closest point.
  3. Unwind – on the way back up, compute the gap between q and the node's split line: |q[axis] − node[axis]|.
  4. Prune or search – if gap ≥ best distance, skip the other subtree; otherwise search it too.
  5. Return – when the recursion finishes, the best point is the nearest neighbour.

The search keeps a circle (a sphere in 3-D) centred on q whose radius is the best distance found so far. Any point on the far side of a split line is at least gap away from q, because it has to cross that line. So if the gap is already as large as the radius, no point over there can win and the whole subtree is pruned — possibly thousands of points skipped with one subtraction.

Descending the near side first matters. It finds a good candidate early, which shrinks the circle, which makes later pruning more likely. On random, well-spread 2-D data the search visits O(log n) nodes on average. In the worst case — points arranged so the circle crosses almost every split — it degrades to O(n).

The same procedure extends to k nearest neighbours: keep the k best points in a max-heap and use the k-th best distance as the radius.

  • Compare squared distances: test gap² ≥ best² and skip the square roots
  • q equal to a stored point: the best distance becomes 0 and every far side is pruned
  • Ties: the first point found at the best distance is kept
Key reference

Terms, operations, and practical uses

Terms to know

  • CellThe rectangular region of space a node owns; the root owns everything.
  • Splitting axisThe coordinate compared at a node: depth mod k.
  • PruningSkipping a subtree because its cell is farther away than the best distance.
  • Curse of dimensionalityIn high dimensions distances concentrate, so pruning rarely fires.

Related lessons

  • Binary search treesThe one-key version: compare, go left or right.
  • QuadtreesSplit both axes at once into four quadrants.
  • Interval treesAnother augmented tree, for overlapping ranges.
  • HeapsThe max-heap that holds the k best candidates in k-NN search.
Implementation

Code in Python, C++ and Java

import math


class Node:
    def __init__(self, point, axis, left=None, right=None):
        self.point = point
        self.axis = axis
        self.left = left
        self.right = right


def build(points, depth=0):
    if not points:
        return None
    axis = depth % 2
    points = sorted(points, key=lambda p: p[axis])
    mid = len(points) // 2
    return Node(
        points[mid],
        axis,
        build(points[:mid], depth + 1),
        build(points[mid + 1 :], depth + 1),
    )


def nearest(node, query, best=None, visited=None):
    if node is None:
        return best
    visited.append(node.point)
    if best is None or math.dist(query, node.point) < math.dist(query, best):
        best = node.point

    diff = query[node.axis] - node.point[node.axis]
    near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)
    best = nearest(near, query, best, visited)
    # The far side can only help if the splitting line is closer than the
    # best point found so far.
    if abs(diff) < math.dist(query, best):
        best = nearest(far, query, best, visited)
    return best


def preorder(node):
    if node is None:
        return []
    return [node.point] + preorder(node.left) + preorder(node.right)


points = [(7, 2), (5, 4), (9, 6), (2, 3), (4, 7), (8, 1)]
root = build(points)
print("preorder:", " ".join(f"({x},{y})" for x, y in preorder(root)))

visited = []
query = (4, 5)
best = nearest(root, query, visited=visited)
print(f"nearest to ({query[0]},{query[1]}) is ({best[0]},{best[1]}) at distance", round(math.dist(query, best), 3))
print("visited", len(visited), "of", len(points), "nodes")
#include <algorithm>
#include <cmath>
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

struct Point {
    double x[2];
};

struct Node {
    Point point;
    int axis;
    unique_ptr<Node> left, right;
};

unique_ptr<Node> build(vector<Point> pts, int depth) {
    if (pts.empty()) return nullptr;
    int axis = depth % 2;
    sort(pts.begin(), pts.end(),
         [axis](const Point& a, const Point& b) { return a.x[axis] < b.x[axis]; });
    size_t mid = pts.size() / 2;
    auto node = make_unique<Node>();
    node->point = pts[mid];
    node->axis = axis;
    node->left = build(vector<Point>(pts.begin(), pts.begin() + mid), depth + 1);
    node->right = build(vector<Point>(pts.begin() + mid + 1, pts.end()), depth + 1);
    return node;
}

double dist(const Point& a, const Point& b) {
    return hypot(a.x[0] - b.x[0], a.x[1] - b.x[1]);
}

void nearest(const Node* node, const Point& q, const Point*& best, int& visited) {
    if (!node) return;
    visited++;
    if (!best || dist(q, node->point) < dist(q, *best)) best = &node->point;

    double diff = q.x[node->axis] - node->point.x[node->axis];
    const Node* nearSide = diff < 0 ? node->left.get() : node->right.get();
    const Node* farSide = diff < 0 ? node->right.get() : node->left.get();
    nearest(nearSide, q, best, visited);
    // The far side can only help if the splitting line is closer than the
    // best point found so far.
    if (fabs(diff) < dist(q, *best)) nearest(farSide, q, best, visited);
}

void preorder(const Node* node) {
    if (!node) return;
    cout << " (" << node->point.x[0] << "," << node->point.x[1] << ")";
    preorder(node->left.get());
    preorder(node->right.get());
}

int main() {
    vector<Point> points = {{{7, 2}}, {{5, 4}}, {{9, 6}}, {{2, 3}}, {{4, 7}}, {{8, 1}}};
    auto root = build(points, 0);
    cout << "preorder:";
    preorder(root.get());
    cout << "\n";

    Point query = {{4, 5}};
    const Point* best = nullptr;
    int visited = 0;
    nearest(root.get(), query, best, visited);
    cout << "nearest to (4,5) is (" << best->x[0] << "," << best->x[1]
         << ") at distance " << round(dist(query, *best) * 1000) / 1000 << "\n";
    cout << "visited " << visited << " of " << points.size() << " nodes\n";
    return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Node(double[] point, int axis, Node left, Node right) {}

    static Node build(double[][] pts, int depth) {
        if (pts.length == 0) return null;
        int axis = depth % 2;
        double[][] sorted = pts.clone();
        Arrays.sort(sorted, Comparator.comparingDouble(p -> p[axis]));
        int mid = sorted.length / 2;
        return new Node(sorted[mid], axis,
                build(Arrays.copyOfRange(sorted, 0, mid), depth + 1),
                build(Arrays.copyOfRange(sorted, mid + 1, sorted.length), depth + 1));
    }

    static double dist(double[] a, double[] b) {
        return Math.hypot(a[0] - b[0], a[1] - b[1]);
    }

    static double[] nearest(Node node, double[] q, double[] best, List<double[]> visited) {
        if (node == null) return best;
        visited.add(node.point());
        if (best == null || dist(q, node.point()) < dist(q, best)) best = node.point();

        double diff = q[node.axis()] - node.point()[node.axis()];
        Node near = diff < 0 ? node.left() : node.right();
        Node far = diff < 0 ? node.right() : node.left();
        best = nearest(near, q, best, visited);
        // The far side can only help if the splitting line is closer than the
        // best point found so far.
        if (Math.abs(diff) < dist(q, best)) best = nearest(far, q, best, visited);
        return best;
    }

    static void preorder(Node node, StringBuilder out) {
        if (node == null) return;
        out.append(String.format("(%.0f,%.0f) ", node.point()[0], node.point()[1]));
        preorder(node.left(), out);
        preorder(node.right(), out);
    }

    public static void main(String[] args) {
        double[][] points = {{7, 2}, {5, 4}, {9, 6}, {2, 3}, {4, 7}, {8, 1}};
        Node root = build(points, 0);
        StringBuilder order = new StringBuilder();
        preorder(root, order);
        System.out.println("preorder: " + order.toString().trim());

        double[] query = {4, 5};
        List<double[]> visited = new ArrayList<>();
        double[] best = nearest(root, query, null, visited);
        System.out.printf("nearest to (4,5) is (%.0f,%.0f) at distance %.3f%n",
                best[0], best[1], dist(query, best));
        System.out.println("visited " + visited.size() + " of " + points.length + " nodes");
    }
}
Watch it run

Step through it

Running on points (7,2) (5,4) (9,6) (2,3) (4,7) (8,1); query (4,5)

0551010(7,2)(5,4)(9,6)(2,3)(4,7)(8,1)k = 2: each point has an x and a y0551010(7,2)(5,4)(9,6)(2,3)(4,7)(8,1)k = 2: each point has an x and a y
Step 1

Six points in the plane

A k-d tree stores k-dimensional points so that a query can skip whole regions. Here k = 2. Nothing is stored yet, so a nearest-point query would have to measure all six points.

Output
1 / 15
4

Range Search

A range search, or orthogonal range query, reports every point inside an axis-aligned box, such as 2 ≤ x ≤ 6 and 3 ≤ y ≤ 8. Walk from the root; at each node, report its point if it lies in the box, then descend into a child only if that child's cell overlaps the box. A cell that lies entirely inside the box can be reported in full without further tests.

For a balanced 2-d tree the cost is O(√n + m), where m is the number of points reported. The √n term comes from the cells that the box's edges cut through: a vertical line can cross only O(√n) cells of a 2-d tree. In k dimensions the bound is O(n¹⁻¹ᐟᵏ + m).

  • Every node holds a point, so internal nodes are tested too, not only leaves
  • Decide whether the box edges are inclusive before you code the overlap test
5

Cost of Each Operation

The bounds below assume a tree built by median splits. An insertion-built tree can be as tall as n, and then every operation that walks a path becomes O(n).

Operations on n points (balanced tree)
OperationAverageWorst case
Build (median split)O(n log n)O(n log n)
InsertO(log n)O(n)
Search for an exact pointO(log n)O(n)
Nearest neighbourO(log n)O(n)
Range search (2-D)O(√n + m)O(√n + m)
SpaceO(n)O(n)
  • Exact search follows one path, like a BST lookup
  • Delete is awkward: the replacement must be the minimum on the node's own axis from its right subtree
6

Limits and Applications

These trees work well while the number of points is much larger than 2ᵏ. As k grows, the curse of dimensionality sets in: in high dimensions almost every point is roughly the same distance from q, the search circle crosses nearly every split, and pruning stops working. Above about 10–20 dimensions the tree is often no faster than a linear scan, and approximate methods (locality-sensitive hashing, graph-based indexes such as HNSW) take over.

In low dimensions they are everywhere: nearest neighbour search in 2-D and 3-D maps, collision and proximity queries in games and robotics, colour quantisation (points in RGB space), and the k-nearest-neighbours classifier in machine-learning libraries such as scikit-learn, whose KDTree is this structure.

Related spatial structures compared
StructureSplitChildrenBest for
K-d treeOne axis per level, at a point2Nearest neighbour on static low-dimensional points
QuadtreeBoth axes at once, at the cell centre42-D regions, images, uneven density
R-treeBounding rectangles that may overlapManyRectangles and disk-based databases
Ball treeHyperspheres2Higher dimensions, non-Euclidean metrics
  • Best when n ≫ 2ᵏ and k is small
  • Prefer an R-tree when the data are rectangles or live on disk