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)
| 10 | |
| 11 | |
| 12 | def 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 | ) |