如何在每个节点上增长四叉树

How to grow that Quadtree at each node

我制作了一个四叉树,它最初是一个统一的 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.js 使用不同的名称。如果你想隐藏 struct Node 的定义,使用这个:

struct Node {
  int level;
  double xy[2];
  struct Node *child[4];
};

typedef struct Node Node;