我做了一个Quadtree,它最初是一个统一的2级四叉树。
struct qnode {
int level;
double xy[2];
struct qnode *child[4];
};
typedef struct qnode Node;
int main( int argc, char **argv ) {
Node *head;
// make the head node
head = makeNode( 0.0,0.0, 0 );
// make a tree
//full level 2 tree
makeChildren( head );
makeChildren( head->child[0] );
makeChildren( head->child[1] );
makeChildren( head->child[2] );
makeChildren( head->child[3] );
}
//在给定位置(x,y)和级别创建节点
Node *makeNode( double x, double y, int level ) {
int i;
Node *node = (Node *)malloc(sizeof(Node));
node->level = level;
node->xy[0] = x;
node->xy[1] = y;
for( i=0;i<4;++i )
node->child[i] = NULL;
return node;
}
//将叶节点拆分为4个子节点
void makeChildren( Node *parent ) {
double x = parent->xy[0];
double y = parent->xy[1];
int level = parent->level;
double hChild = pow(2.0,-(level+1));
parent->child[0] = makeNode( x,y, level+1 );
parent->child[1] = makeNode( x+hChild,y, level+1 );
parent->child[2] = makeNode( x+hChild,y+hChild, level+1 );
parent->child[3] = makeNode( x,y+hChild, level+1 );
return;
}
如何遍历每个节点并在每个节点上统一生长树?
递归方法似乎是正确的。像这样的东西:
void growTree(Node * root) {
for(int i=0; i<4; i++) {
if(root->child[i] == NULL) root->child[i] = makeNode(0,0,root->level+1);
else growTree(root->child[i]);
}
}
我还建议重新设计makeNode
。像这样的东西:
Node *makeNode(double x, double y, Node * node) {
int level = node->level;
// copy old body of makeNode here
}
另外,改为:
typedef struct Node {
int level;
double xy[2];
struct Node *child[4];
} Node;
没有理由为struct Node和Node提供不同的名称。如果要隐藏struct Node的定义,请使用以下命令:
struct Node {
int level;
double xy[2];
struct Node *child[4];
};
typedef struct Node Node;