Sub topic 4
Building a balanced k-d tree
This chapter assumes you know binary search trees, recursion, Big-O notation, and basic Python tuples and lists. You will turn a list of points into a k-d tree whose height stays near log₂ n.
The construction rule
A k-d tree stores one point in every node. Each node also has a splitting axis, and the points in its two subtrees are separated along that axis. Building the tree takes three steps:
- Pick the axis for the current depth with
depth % k, wherekis the number of dimensions. In 2D the axes alternate x, y, x, y. - Sort the points on that axis and take the median as the node.
- Build the left subtree from the points before the median and the right subtree from the points after it.
Choosing the median means each side gets about half the points. Choosing the first point or a random point could produce a tall, lopsided tree, and search time grows with height.
The code
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 height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
points = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
tree = build(points)
print(tree.point, tree.axis)
print(tree.left.point, tree.right.point)
print(height(tree))The output is:
(7, 2) 0
(5, 4) (9, 6)
3Here is how the root was chosen. Sorted by x, the points are (2,3), (4,7), (5,4), (7,2), (8,1), (9,6). Index 6 // 2 = 3 is (7, 2), so it becomes the root. Three points go left and two go right. The next level sorts by y, so the left child is (5, 4) and the right child is (9, 6).
Cost of building
Each level sorts every point once, which costs O(n log n) per level. The tree has about log₂ n levels, so this build takes O(n log² n) time. You can lower it to O(n log n) by finding the median with a linear-time selection algorithm such as quickselect instead of sorting. The tree uses O(n) space, one node per point.
The size rule len(points) // 2 keeps the two sides within one point of each other, so the height is at most ⌊log₂ n⌋ + 1.
Common errors
- Slicing mistakes. Use
points[:mid]andpoints[mid + 1:]. Writingpoints[mid:]for the right side keeps the median in the tree twice, and the recursion never shrinks that side. - Axis taken from the wrong depth. Pass
depth + 1to both recursive calls. If you forget, every level splits on x. - Duplicate coordinates. Several points can share the median's value on the split axis. Some of them end up in the left subtree and some in the right. When you search, compare with
<=and>=and don't assume that the left side is strictly smaller. - Mutating the input.
sortedreturns a new list, so the caller's list is unchanged. Callingpoints.sort()would reorder the list the caller passed in.
Exercise
You build a k-d tree from 1,000,000 two-dimensional points using the median-split method above. Roughly how many levels does the tree have, and which step of the build dominates the cost?
Show answer
About 20 levels, since log₂(1,000,000) is about 20. The sort at each node dominates. Every level sorts all n points in total, which gives O(n log² n) overall. Replacing the sort with a linear-time median selection reduces this to O(n log n).