提供的代码创建一个
k-d tree.您可以使用它在矩形上绘制线条,将其划分为更小的矩形.获得树后,可以按如下方式使用它将区域划分为这些矩形:
>在树的根部选择节点.
>通过这一点绘制一条垂直线.
>选择它的左子,在你刚刚通过它的父线绘制的线左侧的这一点画一条水平线(这条线在你刚绘制的线上停止).
>选择它是正确的孩子,在你刚刚通过它的父线绘制的线的右侧绘制一条水平线(此线也在您通过父线绘制的线处停止).
>以递归方式执行此操作,在树的每个级别切换垂直和水平线.
码:
int MAX_HEIGHT = 100;
int MAX_WIDTH = 100;
int NUM_POINTS = 6;
// Generate random list of points
List pointList = new List();
Random rand = new Random();
for(int i = 0; i < NUM_POINTS ; i++)
{
pointList.add(new Point(rand.nextInt(MAX_HEIGHT), rand.nextInt(MAX_WIDTH));
}
BinaryTree tree = CreateKDTree(pointList, 0);
// Recursive function for creating a K-D Tree from a list of points
// This tree can be used to draw lines that divide the space up
// into rectangles.
public BinaryTree CreateKDTree(List pointList, int depth)
{
// Have to create the PointComparator class that just selects the
// specified coordinate and sorts based on that
Coordinate coord= depth % 2 == 0 ? X_COORDINATE : Y_COORDINATE
Collections.sort(pointList, new PointComparator(coord));
int median = pointList.size() / 2;
// unfortunately Java doesn't have a BinaryTree structure so
// you have to create this too
BinaryTree node = new BinaryTree(pointList[median]);
if(pointList.size() == 1) return node;
if(median > 0)
node.left(CreateKDTree(pointList.subList(0, median), depth + 1);
if(median + 1 < subList.size())
node.right(CreateKDTree(pointList.subList(median + 1, subList.size()), depth + 1);
return node;
}