kd_tree.rb

lib/containers/kd_tree.rb
Last Update: 2013-05-16 14:38:07 -0400

A kd-tree is a binary tree that allows one to store points (of any space dimension: 2D, 3D, etc). The structure of the resulting tree makes it so that large portions of the tree are pruned during queries.

One very good use of the tree is to allow nearest neighbor searching. Let’s say you have a number of points in 2D space, and you want to find the nearest 2 points from a specific point:

First, put the points into the tree:

kdtree = Containers::KDTree.new( {0 => [4, 3], 1 => [3, 4], 2 => [-1, 2], 3 => [6, 4],
                                 4 => [3, -5], 5 => [-2, -5] })

Then, query on the tree:

puts kd.find_nearest([0, 0], 2) => [[5, 2], [9, 1]]

The result is an array of [distance, id] pairs. There seems to be a bug in this version.

Note that the point queried on does not have to exist in the tree. However, if it does exist, it will be returned.