用C语言代码实现编写一个四叉树
时间: 2023-04-06 16:02:33 浏览: 209
我可以回答这个问题。四叉树是一种数据结构,它可以用于空间划分和查询。以下是一个简单的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_POINTS 10
typedef struct point {
int x;
int y;
} Point;
typedef struct quadtree {
Point point;
struct quadtree* nw;
struct quadtree* ne;
struct quadtree* sw;
struct quadtree* se;
} Quadtree;
Quadtree* create_quadtree(int x1, int y1, int x2, int y2) {
Quadtree* quadtree = (Quadtree*)malloc(sizeof(Quadtree));
quadtree->point.x = (x1 + x2) / 2;
quadtree->point.y = (y1 + y2) / 2;
quadtree->nw = NULL;
quadtree->ne = NULL;
quadtree->sw = NULL;
quadtree->se = NULL;
return quadtree;
}
void insert_point(Quadtree* quadtree, Point point) {
if (quadtree == NULL) {
return;
}
if (quadtree->nw == NULL && quadtree->ne == NULL && quadtree->sw == NULL && quadtree->se == NULL) {
quadtree->point = point;
return;
}
if (point.x < quadtree->point.x && point.y < quadtree->point.y) {
if (quadtree->nw == NULL) {
quadtree->nw = create_quadtree(0, 0, quadtree->point.x, quadtree->point.y);
}
insert_point(quadtree->nw, point);
} else if (point.x >= quadtree->point.x && point.y < quadtree->point.y) {
if (quadtree->ne == NULL) {
quadtree->ne = create_quadtree(quadtree->point.x, 0, MAX_POINTS, quadtree->point.y);
}
insert_point(quadtree->ne, point);
} else if (point.x < quadtree->point.x && point.y >= quadtree->point.y) {
if (quadtree->sw == NULL) {
quadtree->sw = create_quadtree(0, quadtree->point.y, quadtree->point.x, MAX_POINTS);
}
insert_point(quadtree->sw, point);
} else {
if (quadtree->se == NULL) {
quadtree->se = create_quadtree(quadtree->point.x, quadtree->point.y, MAX_POINTS, MAX_POINTS);
}
insert_point(quadtree->se, point);
}
}
void print_quadtree(Quadtree* quadtree) {
if (quadtree == NULL) {
return;
}
printf("(%d, %d)\n", quadtree->point.x, quadtree->point.y);
print_quadtree(quadtree->nw);
print_quadtree(quadtree->ne);
print_quadtree(quadtree->sw);
print_quadtree(quadtree->se);
}
int main() {
Quadtree* quadtree = create_quadtree(0, 0, MAX_POINTS, MAX_POINTS);
Point points[MAX_POINTS] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}, {17, 18}, {19, 20}};
for (int i = 0; i < MAX_POINTS; i++) {
insert_point(quadtree, points[i]);
}
print_quadtree(quadtree);
return 0;
}
```
这个代码实现了一个简单的四叉树,可以插入点并打印整个四叉树。
阅读全文