面试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)
相关推荐
闪电麦坤9513 小时前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
易木木木响叮当20 小时前
有限元方法中的数值技术:行列式、求逆、矩阵方程
线性代数·矩阵
闪电麦坤951 天前
数据结构:N叉树 (N-ary Tree)
数据结构·
梁辰兴1 天前
数据结构:串、数组与广义表
开发语言·数据结构·c··数组·广义表
东方佑2 天前
UniVoc:基于二维矩阵映射的多语言词汇表系统
人工智能·算法·矩阵
火车叨位去19493 天前
力扣top100(day01-05)--矩阵
算法·leetcode·矩阵
厦门辰迈智慧科技有限公司3 天前
现代化水库运行管理矩阵建设的要点
运维·网络·物联网·线性代数·安全·矩阵·监测
文弱_书生4 天前
为什么神经网络的权重矩阵具有低秩特性?如何理解和解释?
人工智能·神经网络·矩阵
没有bug.的程序员6 天前
《常见高频算法题 Java 解法实战精讲(1):链表与数组》
java·算法·链表·数组
夜斗小神社6 天前
【LeetCode 热题 100】(六)矩阵
算法·leetcode·矩阵