k-d tree
Given a list of n points, the following algorithm will construct a balanced kd-tree containing those points.
function kdtree (list of points pointList, int depth) { if pointList is empty return nil; else { // Select axis based on depth so that axis cycles through all valid values var int axis := depth mod k; // Sort point list and choose median as pivot element select median from pointList; // Create node and construct subtrees var tree_node node; node.location := median; node.leftChild := kdtree(points in pointList before median, depth+1); node.rightChild := kdtree(points in pointList after median, depth+1); return node; } }
This algorithm implemented in the Python programming language is as follows:
Node:
kdtreepointList, depth=:
pointList:
k = pointList
axis = depth % k
pointList.sort= x,y:xaxis,yaxis
median = pointList/
node = Node
node.location = pointListmedian
node.leftChild = kdtreepointList:median, depth
node.rightChild = kdtreepointListmedian:, depth
node
example:
pointList = [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)] tree = kdtree(pointList) Balancing a kd-tree: http://en.wikipedia.org/wiki/Kd-tree