面试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)
相关推荐
deep_drink2 小时前
【基础知识一】线性代数的核心:从矩阵变换到 SVD 终极奥义
线性代数·机器学习·矩阵
数智工坊4 小时前
【数据结构-特殊矩阵】3.5 特殊矩阵-压缩存储
数据结构·线性代数·矩阵
AI科技星4 小时前
张祥前统一场论核心场方程的经典验证-基于电子与质子的求导溯源及力的精确计算
线性代数·算法·机器学习·矩阵·概率论
deep_drink6 小时前
【基础知识二】彻底读懂拉普拉斯矩阵 (Laplacian)
人工智能·深度学习·线性代数·矩阵
Amber勇闯数分9 小时前
【Hive】基于物品协同过滤 [ ItemCF ] 推荐课程-余弦相似度计算
大数据·数据仓库·hive·hadoop·矩阵
Tisfy1 天前
LeetCode 3637.三段式数组 I:一次遍历(三种实现)
算法·leetcode·题解·模拟·数组·遍历·moines
跨境卫士情报站1 天前
用“渠道矩阵+内容节奏”把流量做成可控资产
大数据·人工智能·矩阵·产品运营·跨境电商·亚马逊
sonadorje1 天前
欧氏内积(Euclidean Inner Product)
线性代数·矩阵
2401_841495641 天前
【LeetCode刷题】对称二叉树
数据结构·python·算法·leetcode·二叉树··递归
geffen16882 天前
8K/4K无缝高清混合混插矩阵
矩阵