MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / build_kdtree

Function build_kdtree

data_structures/kd_tree/build_kdtree.py:12–43  ·  view source on GitHub ↗

Builds a KD-Tree from a list of points. Args: points: The list of points to build the KD-Tree from. depth: The current depth in the tree (used to determine axis for splitting). Returns: The root node of the KD-Tree, o

(points: list[list[float]], depth: int = 0)

Source from the content-addressed store, hash-verified

10
11
12def build_kdtree(points: list[list[float]], depth: int = 0) -> KDNode | None:
13 """
14 Builds a KD-Tree from a list of points.
15
16 Args:
17 points: The list of points to build the KD-Tree from.
18 depth: The current depth in the tree
19 (used to determine axis for splitting).
20
21 Returns:
22 The root node of the KD-Tree,
23 or None if no points are provided.
24 """
25 if not points:
26 return None
27
28 k = len(points[0]) # Dimensionality of the points
29 axis = depth % k
30
31 # Sort point list and choose median as pivot element
32 points.sort(key=lambda point: point[axis])
33 median_idx = len(points) // 2
34
35 # Create node and construct subtrees
36 left_points = points[:median_idx]
37 right_points = points[median_idx + 1 :]
38
39 return KDNode(
40 point=points[median_idx],
41 left=build_kdtree(left_points, depth + 1),
42 right=build_kdtree(right_points, depth + 1),
43 )

Callers 4

mainFunction · 0.90
test_build_kdtreeFunction · 0.90
test_edge_casesFunction · 0.90

Calls 2

KDNodeClass · 0.90
sortMethod · 0.80

Tested by 3

test_build_kdtreeFunction · 0.72
test_edge_casesFunction · 0.72