How to iterating a Quad/Oct tree

萝らか妹 提交于 2019-12-05 21:28:51

Iterating over the whole tree is easy, you can do it recursively.

void iterate(node *n) {
    // do something with n
    if (n->child1 != NULL) iterate(n->child1);
    if (n->child2 != NULL) iterate(n->child2);
    if (n->child3 != NULL) iterate(n->child3);
    if (n->child4 != NULL) iterate(n->child4);
}

Then call iterate(root) and the do something will happen on every node in the quadtree.

I suspect this isn't really what you're asking, though. There'd be no point in keeping your data in a quadtree if that's all you were doing. If you want to find a particular node in the quadtree, then you need something else. Let's say you want to find a point x,y in a quadtree. Then you do something like:

void find(node *n, float x, float y) {
    if (x == n->x && y == n->y) // you've found it!
    if (x < n->x) {
        if (y < n->y) {
            if (n->child1 != NULL) {
                find(n->child1, x, y);
            } else {
                // point not in quadtree
            }
        } else {
           ...same, but child2
        }
    } else {
        ...same, child3 & 4
    }
}

Note that quadtrees aren't normally split on the points they store themselves, they are usually split by storing the splitting coordinates separately from the points (which are only stored at the leaves of the quadtree). See the wikipedia picture for an example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!