A C++ implementation of the KD-Tree (k-dimensional tree) data structure, commonly used for organizing points in a k-dimensional space. KD-Trees are widely used in applications such as nearest neighbor search, range queries, and spatial indexing.
- Build a KD-Tree from a set of points in k-dimensional space
- Efficient nearest neighbor search
- Range search queries
- Customizable for any number of dimensions
- Input: A list of points, each with k dimensions.
- Process:
- Start with the entire list of points.
- Select the axis based on the current tree depth (
axis = depth % k). - Sort points by the selected axis.
- Choose the median point as the root for the current subtree.
- Recursively build the left subtree with points before the median.
- Recursively build the right subtree with points after the median.
- Output: A balanced KD-Tree.
- Input: A target point and the KD-Tree.
- Process:
- Start at the root node.
- Compare the target point with the current node along the current axis.
- Recursively search the subtree that could contain the closest point.
- Update the best distance found so far.
- If the hypersphere crosses the splitting plane, search the other subtree.
- Continue until all relevant nodes are checked.
- Output: The nearest neighbor point and its distance.
- Input: A query range and the KD-Tree.
- Process:
- Traverse the tree recursively.
- At each node, check if the point lies within the query range.
- If yes, add it to the result set.
- Decide which subtrees to search based on the range and splitting axis.
- Output: All points within the specified range.
-
Clone the repository:
git clone https://github.com/yourusername/KD-Tree.git cd KD-Tree -
Compile the code:
g++ main.cpp -o kd_tree
-
Run the program:
./kd_tree
Suppose you have a set of 2D points and want to find the nearest neighbor to a query point. The KD-Tree efficiently organizes the points and performs the search in logarithmic time.
main.cpp— Contains the KD-Tree implementation and example usage.README.md— Project documentation.
This project is licensed under the MIT License.
Feel free to customize the example and usage sections to match your actual code