面试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)
相关推荐
superior tigre1 天前
NumPy 基础使用方法(基础+矩阵运算+Attention)
线性代数·矩阵·numpy
计算机安禾1 天前
【数据结构与算法】第38篇:图论(二):深度优先搜索(DFS)与广度优先搜索(BFS)
数据结构·算法·矩阵·排序算法·深度优先·图论·宽度优先
咬_咬1 天前
go语言学习(数组与切片)
开发语言·学习·golang·数组·切片
_日拱一卒1 天前
LeetCode:矩阵置零
java·数据结构·线性代数·算法·leetcode·职场和发展·矩阵
学习永无止境@1 天前
MATLAB中矩阵转置
算法·matlab·fpga开发·矩阵
汀、人工智能1 天前
[特殊字符] 第106课:旋转图像
数据结构·算法·矩阵·数据库架构·数组·旋转图像
Q741_1471 天前
每日一题 3740. 三个相等元素之间的最小距离 I 3741. 三个相等元素之间的最小距离 II 模拟 哈希表 C++ 题解
c++·算法·leetcode·模拟·数组·哈希表
zd8451015001 天前
51单片机-矩阵按键程序代码
矩阵·51单片机
wsoz2 天前
Leetcode普通数组-day5、6
c++·算法·leetcode·数组
nihao5612 天前
机器学习:阈值与混淆矩阵
人工智能·机器学习·矩阵