面试150 建立四叉树

思路

采用递归分治的思路构建四叉树。首先判断当前区域内的值是否全部相同,若是,则构建一个叶子节点;若否,则将区域划分为四个子区域(左上、右上、左下、右下),对每个子区域递归构建对应的子节点,并将其作为当前非叶子节点的四个子树。通过不断划分和合并,实现将二维网格压缩为一棵结构紧凑的四叉树。

python 复制代码
"""
# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""

class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        n=len(grid)
        def isSame(x,y,size):
            val=grid[x][y]
            for i in range(x,x+size):
                for j in range(y,y+size):
                    if grid[i][j]!=val:
                        return False,val
            return True,val
        
        def build(x,y,size):
            same,val=isSame(x,y,size)
            if same:
                return Node(val==1,True)
            else:
                half=size//2
                return Node(
                    val=True,
                    isLeaf=False,
                    topLeft=build(x,y,half),
                    topRight=build(x,y+half,half),
                    bottomLeft=build(x+half,y,half),
                    bottomRight=build(x+half,y+half,half)
                )
        return build(0,0,n)
相关推荐
We་ct6 分钟前
LeetCode 74. 搜索二维矩阵:两种高效解题思路
前端·算法·leetcode·矩阵·typescript·二分查找
Tisfy2 小时前
LeetCode 1886.判断矩阵经轮转后是否一致:模拟
算法·leetcode·矩阵·题解·模拟
Zaly.14 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
2301_766558651 天前
本地部署+云端优化:矩阵跃动龙虾机器人,实现7×24小时AI获客无人值守
人工智能·矩阵·机器人
Tisfy1 天前
LeetCode 3643.垂直翻转子矩阵:原地修改
算法·leetcode·矩阵·模拟
wyiyiyi1 天前
【线性代数】对偶空间与矩阵转置及矩阵分解(Java讲解)
java·线性代数·支持向量机·矩阵·数据分析
Frostnova丶1 天前
LeetCode 3643.子矩阵垂直翻转算法解析
算法·leetcode·矩阵
ryrhhhh1 天前
AI流量闭环搭建指南:矩阵跃动龙虾机器人+GEO,从占位到转化全自动化
人工智能·矩阵·机器人
ryrhhhh1 天前
矩阵跃动自研技术:小陌GEO动态监测算法,30分钟快速适配大模型更新
人工智能·算法·矩阵
2501_943124051 天前
7×24小时自动运营:矩阵跃动龙虾机器人,AI流量闭环效率拉满
人工智能·矩阵·机器人