zoukankan      html  css  js  c++  java
  • kd tree

    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:
    class Node:pass
     
    def kdtree(pointList, depth=0):
        if not pointList:
            return
     
        # Select axis based on depth so that axis cycles through all valid values
        k = len(pointList[0]) # assumes all points have the same dimension
        axis = depth % k
     
        # Sort point list and choose median as pivot element
        pointList.sort(cmp=lambda x,y:cmp(x[axis],y[axis]))
        median = len(pointList)/2 # choose median
     
        # Create node and construct subtrees
        node = Node()
        node.location = pointList[median]
        node.leftChild = kdtree(pointList[0:median], depth+1)
        node.rightChild = kdtree(pointList[median+1:], depth+1)
        return 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
  • 相关阅读:
    javascript中map的用法
    洛谷P1057传球游戏-题解
    洛谷P1049装箱问题-题解
    洛谷P1048采药-题解
    洛谷P1044栈-题解
    洛谷P1040加分二叉树-题解
    洛谷P1005矩阵取数游戏-题解
    洛谷P1004方格取数-题解
    洛谷P1002过河卒-题解
    搜索
  • 原文地址:https://www.cnblogs.com/cutepig/p/1258853.html
Copyright © 2011-2022 走看看