简体   繁体   English

遍历四叉树

[英]Traversing a Quad Tree

I have implemented a Quadtree for sorting points in a graph. 我实现了一个四叉树,用于对图中的点进行排序。 Each time a point falls within a quadrant that already contains a point, the quadrant is subdivided again to allow each point to fall into it's own quadrant. 每次点落入已经包含一个点的象限内时,该象限都会再次细分,以允许每个点落入其自己的象限中。 Each node has the following attributes: 每个节点具有以下属性:

Rectangle bounds; //The bounds of the quadrant
int num = 0; //The number of points in or below this node
Point point; //The point stored in this node. If the quadrant is divided, this is set to null.
Quadtree sub[]; //Pointers to the 4 subdivided quadrants.

Say I wanted to go through every node that is stored in this tree, and count the number of points that fall within the bounds of a given rectangle, how would I go about recursively checking every node in the tree (Assuming I already have methods that check if they fall in a certain region)? 假设我想遍历此树中存储的每个节点,并计算落在给定矩形范围内的点数,那么我将如何递归检查树中的每个节点(假设我已经有方法检查它们是否属于某个区域)?

You would recurse down each node whose bounds overlap with the given rectangle. 您将向下递归其边界与给定矩形重叠的每个节点。

Here's some pseudo code based on the fields that you mention in your question: 这是一些基于您在问题中提到的字段的伪代码:

int countPointsInRect(Quadtree root, Rectangle r) {

    // Entire bound of current node outside of given rectangle?
    if (root.bounds outside r)
        return 0

    // Part, or whole of current bound inside given rectangle:
    // Recurse on each subtree
    int sum = 0
    for (Quadtree q : sub)
        sum += countPointsInRect(q, r)
    return sum
}

You can optimize it slightly by adding the following check before recursing down the subtrees: 您可以通过在递归子树之前添加以下检查来稍微优化它:

    // Entire bound of current node inside given rectangle?
    if (root.bounds inside r)
        return num  // return immediately. No need to recurse

Additional reading: 补充阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM