当前位置: 面试刷题>> 建立四叉树(经典算法150题)


题目描述补充

题目:建立四叉树并实现基本操作

四叉树(Quadtree)是一种树形数据结构,用于在二维空间内对数据进行划分和索引。每个节点代表一个矩形区域,如果该区域被进一步划分为四个子区域(即子节点),则这些子区域可能包含数据或继续被划分为更小的子区域。在图像处理、地理信息系统(GIS)、游戏开发中,四叉树常被用于空间划分和快速检索。

本题要求你实现一个四叉树结构,并提供以下功能:

  1. 构建四叉树:根据给定的二维点集(或矩形区域及其内的点集)构建四叉树。
  2. 插入点:向四叉树中插入新的二维点。
  3. 查询区域:查询给定矩形区域内的所有点。
  4. 遍历四叉树:实现一种遍历方法,如中序遍历,以显示四叉树的结构。

示例代码

以下是使用PHP、Python和JavaScript编写的四叉树实现示例,包括构建四叉树、插入点和遍历四叉树的基本功能。

PHP 示例

class QuadTreeNode {
    public $x, $y, $width, $height;
    public $points = [];
    public $children = [null, null, null, null]; // 左上, 右上, 右下, 左下

    function __construct($x, $y, $width, $height) {
        $this->x = $x;
        $this->y = $y;
        $this->width = $width;
        $this->height = $height;
    }

    // 插入点(简化版,不递归分割)
    function insert($point) {
        if (inRange($point, $this)) {
            $this->points[] = $point;
            // 实际应用中可能需要根据点的密度决定是否继续分割
        }
    }

    // 辅助函数:检查点是否在节点矩形内
    function inRange($point, $node) {
        return $point[0] >= $node->x && $point[0] < $node->x + $node->width &&
               $point[1] >= $node->y && $point[1] < $node->y + $node->height;
    }

    // 遍历(简单的前序遍历)
    function traverse() {
        echo "Node at ($this->x, $this->y) with size ($this->width, $this->height) contains " . count($this->points) . " points\n";
        foreach ($this->children as $child) {
            if ($child !== null) {
                $child->traverse();
            }
        }
    }
}

// 使用示例
$root = new QuadTreeNode(0, 0, 100, 100);
$root->insert([50, 50]);
$root->traverse();

Python 示例

class QuadTreeNode:
    def __init__(self, x, y, width, height):
        self.x, self.y, self.width, self.height = x, y, width, height
        self.points = []
        self.children = [None] * 4  # 左上, 右上, 右下, 左下

    def insert(self, point):
        if self.in_range(point):
            self.points.append(point)
            # 根据需要实现更复杂的插入逻辑

    def in_range(self, point):
        return self.x <= point[0] < self.x + self.width and self.y <= point[1] < self.y + self.height

    def traverse(self, prefix=""):
        print(f"{prefix}Node at ({self.x}, {self.y}) with size ({self.width}, {self.height}) contains {len(self.points)} points")
        for i, child in enumerate(self.children):
            if child:
                child.traverse(prefix + "  ")

# 使用示例
root = QuadTreeNode(0, 0, 100, 100)
root.insert([50, 50])
root.traverse()

JavaScript 示例

class QuadTreeNode {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.points = [];
        this.children = [null, null, null, null]; // 左上, 右上, 右下, 左下
    }

    insert(point) {
        if (this.inRange(point)) {
            this.points.push(point);
            // 复杂情况需进一步处理
        }
    }

    inRange(point) {
        return point[0] >= this.x && point[0] < this.x + this.width &&
               point[1] >= this.y && point[1] < this.y + this.height;
    }

    traverse(prefix = "") {
        console.log(`${prefix}Node at (${this.x}, ${this.y}) with size (${this.width}, ${this.height}) contains ${this.points.length} points`);
        this.children.forEach((child, index) => {
            if (child) {
                child.traverse(prefix + "  ");
            }
        });
    }
}

// 使用示例
const root = new QuadTreeNode(0, 0, 100, 100);
root.insert([50, 50]);
root.traverse();

以上示例展示了如何构建基本的四叉树结构,并实现了插入点和遍历的基本功能。在实际应用中,你可能需要根据具体需求进一步实现如递归分割、查询区域等高级功能。

推荐面试题