LeetCode 427. 建立四叉树

LeetCode 427. 建立四叉树

(题干略)

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":
        return self._construct(grid, 0, 0, len(grid) - 1, len(grid[0]) - 1)

    def _construct(
        self, grid: List[List[int]], x1: int, y1: int, x2: int, y2: int
    ) -> "Node":
        q = (
            x2 - x1 + 1
        ) >> 1  # 给定正方形中四分之一正方形的边长,特别地,q == 0 时,表示该正方形不可再分
        if not q:
            return Node(grid[x1][y1], True, None, None, None, None)
        topLeft = self._construct(grid, x1, y1, x1 + q - 1, y1 + q - 1)
        topRight = self._construct(grid, x1, y1 + q, x1 + q - 1, y2)
        bottomLeft = self._construct(grid, x1 + q, y1, x2, y1 + q - 1)
        bottomRight = self._construct(grid, x1 + q, y1 + q, x2, y2)
        # 有四个叶子节点,且值相同就向上合并为新的叶子节点
        if (
            topLeft.isLeaf
            and topRight.isLeaf
            and bottomLeft.isLeaf
            and bottomRight.isLeaf
            and topLeft.val == topRight.val == bottomLeft.val == bottomRight.val
        ):
            return Node(topLeft.val, True, None, None, None, None)
        else:
            return Node(0, False, topLeft, topRight, bottomLeft, bottomRight)

时间复杂度

本题是经典的基于分治思想写出的递归解法,假设每个边长为n的矩形区域耗时为T(n),显然T(1) = O(1),则 T(n) = 4 T(n/2) + O(1),根据主定理可以求得时间复杂度为 O(n^2)

空间复杂度

空间复杂度为递归所占用的最大栈深度,算法整个栈的搜索空间为一颗完全四叉树,最深层的叶子节点为n^2个,最大栈深度就是二叉树的高度,有公式 4^(h-1) = n^2,则空间复杂度为 O(logn)

相关推荐
Brookty28 分钟前
【算法】双指针(二)复写零
学习·算法
胖达不服输44 分钟前
「日拱一码」081 机器学习——梯度增强特征选择GBFS
人工智能·python·算法·机器学习·梯度增强特征选择·gbfs
初级炼丹师(爱说实话版)1 小时前
2025算法八股——深度学习——优化器小结
人工智能·深度学习·算法
努力的小帅1 小时前
C++_哈希
开发语言·c++·学习·算法·哈希算法·散列表
Christo32 小时前
TFS-2023《Fuzzy Clustering With Knowledge Extraction and Granulation》
人工智能·算法·机器学习·支持向量机
过河卒_zh15667662 小时前
AI内容标识新规实施后,大厂AI用户协议有何变化?(二)百度系
人工智能·算法·aigc·算法备案·生成合成类算法备案
薰衣草23332 小时前
滑动窗口(2)——不定长
python·算法·leetcode
金融小师妹4 小时前
基于哈塞特独立性表态的AI量化研究:美联储政策独立性的多维验证
大数据·人工智能·算法
纪元A梦7 小时前
贪心算法应用:化工反应器调度问题详解
算法·贪心算法
深圳市快瞳科技有限公司8 小时前
小场景大市场:猫狗识别算法在宠物智能设备中的应用
算法·计算机视觉·宠物