我制作了一个四叉树,最初是一个统一的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;
}
如何遍历每个节点并在每个节点上均匀地生长树?
答案 0 :(得分:1)
递归方法似乎是正确的。像这样:
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 {
int level;
double xy[2];
struct Node *child[4];
};
typedef struct Node Node;