Sub topic 3
What a K-d Tree Stores and How It Splits
This chapter assumes you know binary search trees, recursion, basic Python classes and tuples, and Euclidean distance. It describes the shape of a k-d tree and the rule that governs it. The next chapter covers how to build one efficiently.
What a node holds
A k-d tree is a binary tree over points in k dimensions. The "k" is the number of coordinates per point. Each node stores three things:
- One data point, such as
(7, 2). - An axis, the coordinate index this node splits on (0 for x, 1 for y).
- Two children,
leftandright, either of which may be empty.
Each node does two jobs. It is a stored point, and it also defines a splitting hyperplane. In 2D this is a vertical or horizontal line through the node's point. In 3D it is a plane.
The ordering rule
A binary search tree compares one key at every level. A k-d tree compares a different coordinate at each level.
For a node that splits on axis a:
- Every point in the left subtree has a coordinate on axis
aless than or equal to the node's. - Every point in the right subtree has a coordinate on axis
agreater than or equal to the node's.
The usual way to choose the axis is to cycle with depth: axis = depth % k. In 2D the root splits on x, its children on y, their children on x again, and so on.
Each node owns a region
Every node also covers a rectangular region of space. The root covers everything. Each split cuts the parent's region in two, and each child gets one half. A point in the left subtree lies in the left half, so the node's coordinate acts as a boundary for its whole subtree.
This is why k-d trees support pruning. If a query area lies entirely on one side of a splitting line, the other subtree cannot contain a match, and the search skips it.
A concrete tree
The code below builds a tree from six points and prints its shape. It reuses the Node and build pattern from the chapter on construction, so treat build as a black box for now.
class Node:
def __init__(self, point, axis, left, right):
self.point = point
self.axis = axis
self.left = left
self.right = right
def build(points, depth=0):
if not points:
return None
k = len(points[0])
axis = depth % k
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 show(node, depth=0, side="root"):
if node is None:
return
print(" " * depth + f"{side}: {node.point} splits on {'xyz'[node.axis]}")
show(node.left, depth + 1, "left")
show(node.right, depth + 1, "right")
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
show(build(points))Output:
root: (7, 2) splits on x
left: (5, 4) splits on y
left: (2, 3) splits on x
right: (4, 7) splits on x
right: (9, 6) splits on y
left: (8, 1) splits on xThe root (7, 2) splits on x. Everything in its left subtree has x at most 7, and everything in its right subtree has x at least 7. At depth 1 the nodes compare y, and at depth 2 the comparison returns to x.
Common mistakes
- Reading the tree like a BST on one key. Comparing a target's x at every level gives wrong answers. Always compare on
node.axis. - Forgetting the point belongs to the node. The splitting point is stored in the node and is not repeated in either subtree. Range and nearest-neighbor searches must check it as a candidate.
- Assuming the axis must cycle. Cycling is a convention. Some implementations split on the axis with the widest spread. Storing
axisin each node keeps the search code the same either way.
Exercise
In the tree above, you want all points with x less than 6. At the root (7, 2), which subtree can you skip, and why?
Show answer
Skip the right subtree. The root splits on x, and every point on the right has x at least 7, so none can have x less than 6. You still check the root itself (x = 7 fails the test) and search the left subtree.