面试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)
相关推荐
吃好睡好便好17 小时前
矩阵的乘法运算
数据结构·人工智能·学习·线性代数·算法·matlab·矩阵
Dlrb121121 小时前
数据结构-树与二叉树
数据结构·二叉树·深度优先··广度优先·层序遍历
云登指纹浏览器1 天前
多账号矩阵运营环境隔离方案对比:3种技术路径深度测评
大数据·人工智能·矩阵
吃好睡好便好1 天前
矩阵的求幂运算
人工智能·学习·线性代数·算法·matlab·矩阵
会Tk矩阵群控的小木1 天前
深入解析tk矩阵系统ADB实时投屏与多设备控制实现
运维·线性代数·adb·矩阵·个人开发
跨境技工小黎1 天前
2026海外社媒新玩法:如何用AI批量运营海外社媒矩阵?
人工智能·线性代数·矩阵
YL200404261 天前
064搜索二维矩阵
算法·leetcode·矩阵
吃好睡好便好1 天前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
Agent手记1 天前
跨境电商如何用AI Agent自动运营多平台店铺?企业级「龙虾」矩阵智能体全流程落地指南
大数据·人工智能·ai·矩阵
吃好睡好便好1 天前
创建魔方矩阵和单位矩阵
开发语言·人工智能·学习·线性代数·matlab·矩阵