#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Trees

K-Dimensional Tree in Data Structure

A K-D Tree (K-Dimensional Tree) is a binary tree used to organize points in a k-dimensional space, enabling efficient operations like nearest-neighbor search and range search.

How It Works

At each level of the tree, points are split along one of the k dimensions, cycling through dimensions as depth increases (e.g., split by x at depth 0, by y at depth 1, back to x at depth 2, and so on for 2D points). The median point along the chosen dimension becomes the node, dividing the remaining points into left and right subtrees.

class KDNode:
    def __init__(self, point, left=None, right=None):
        self.point = point
        self.left = left
        self.right = right

def build_kdtree(points, depth=0):
    if not points:
        return None
    k = len(points[0])
    axis = depth % k
    points.sort(key=lambda p: p[axis])
    median = len(points) // 2
    return KDNode(
        point=points[median],
        left=build_kdtree(points[:median], depth + 1),
        right=build_kdtree(points[median + 1:], depth + 1)
    )

Complexity

OperationAverage Time
BuildO(n log n)
Nearest Neighbor SearchO(log n)
Range SearchO(sqrt(n) + m), m = results found

Applications

  • Nearest-neighbor search in machine learning (e.g., k-NN classification).
  • Spatial indexing in GIS and mapping applications.
  • Collision detection in computer graphics and games.
  • Database indexing for multi-dimensional data.

Building a 2-D Tree by Hand

Working through a small example makes the splitting rule concrete. Take six points: (2,3), (5,4), (9,6), (4,7), (8,1) and (7,2).

  1. Depth 0, split on x. Sorted by x the points are (2,3), (4,7), (5,4), (7,2), (8,1), (9,6). The median is (7,2), so it becomes the root. Points with smaller x go left, larger x go right.
  2. Depth 1, split on y (left side). The left group (2,3), (5,4), (4,7) sorted by y gives the median (5,4). Then (2,3) goes to its left and (4,7) to its right.
  3. Depth 1, split on y (right side). The right group (8,1), (9,6) sorted by y gives the median (9,6), with (8,1) as its left child.
            (7,2)  split x
           /      \
      (5,4)        (9,6)   split y
      /    \       /
  (2,3)  (4,7)  (8,1)

Each node is a vertical or horizontal line that divides the plane, and every subtree covers a smaller rectangle of space.

Nearest-Neighbour Search with Pruning

The real power of a K-D tree is that it can skip whole regions of space. To find the closest point to a query, the search goes down the side of each split that contains the query, records the best point so far, and then checks the other side only if it could hold something closer.

def dist2(a, b):
    return sum((x - y) ** 2 for x, y in zip(a, b))

def nearest(node, target, depth=0, best=None):
    if node is None:
        return best
    axis = depth % len(target)

    if best is None or dist2(node.point, target) < dist2(best, target):
        best = node.point

    diff = target[axis] - node.point[axis]
    near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)

    best = nearest(near, target, depth + 1, best)
    if diff ** 2 < dist2(best, target):      # could the other side be closer?
        best = nearest(far, target, depth + 1, best)
    return best

Trace a query at (9,2) on the tree above. At the root (7,2) the squared distance is 4, so it becomes the best. The query's x is 9, so the search goes right to (9,6), whose squared distance is 16. The query's y of 2 is below 6, so it goes left to (8,1) with a squared distance of 2, the new best. Back at the root, the gap to the splitting line x = 7 is 2, and 2 squared is 4, which is larger than the best of 2. The entire left subtree is pruned without visiting a single node in it. The answer is (8,1).

Limits, Alternatives and Practical Tips

  • High dimensions hurt. As k grows, the pruning test rarely succeeds and the search visits most nodes. A common rule of thumb is that K-D trees work well only when the number of points is much larger than 2 to the power of k.
  • Worst cases exist. The quoted search times are averages for well-balanced trees and spread-out data. A badly skewed tree can degrade nearest-neighbour search to O(n).
  • Insertions unbalance the tree. Adding many points after building lets branches grow uneven. Rebuilding periodically keeps queries fast.
  • Sorting cost. The builder shown earlier sorts at every level, which costs O(n log² n) overall. Pre-sorting or a linear-time median selection brings it down to O(n log n). It also sorts the caller's list in place, so pass a copy if the order matters.
StructureBest suited for
K-D treeLow-dimensional points that rarely change
Ball treeModerate dimensions and non-Euclidean distances
R-treeRectangles and shapes in maps and spatial databases
Approximate methods (LSH, HNSW)Very high-dimensional vectors such as embeddings

In real projects you rarely write your own. Both scipy.spatial.KDTree and scikit-learn's KDTree are well tested, and scikit-learn's nearest-neighbour models can choose between a K-D tree and a ball tree automatically.