• 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
  • 相关阅读:
    立方体的形成
    三维变换
    实现任意元素居中
    多个transform 属性案例
    旋转轴心案例
    codeforces 706B B. Interesting drink(二分)
    codeforces 706A A. Beru-taxi(水题)
    hdu-5831 Rikka with Parenthesis II(贪心)
    hdu-5826 physics(数学)
    hdu-5813 Elegant Construction(贪心)
  • 原文地址:https://www.cnblogs.com/cutepig/p/1258853.html
Copyright © 2020-2023  润新知