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)

相关推荐
liujing1023292922 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
2401_881244401 小时前
Treap树
数据结构·算法
乌萨奇也要立志学C++1 小时前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法
网安INF1 小时前
深度学习中的逻辑回归:从原理到Python实现
人工智能·python·深度学习·算法·逻辑回归
wsxqaz1 小时前
浏览器原生控件上传PDF导致hash值不同
算法·pdf·哈希算法
NAGNIP2 小时前
Transformer注意力机制——MHA&MQA&GQA
人工智能·算法
摘星编程2 小时前
多模态AI Agent技术栈解析:视觉-语言-决策融合的算法原理与实践
人工智能·算法·多模态ai·视觉语言融合·ai决策算法
NAGNIP2 小时前
一文搞懂KV-Cache
人工智能·算法
CoovallyAIHub2 小时前
RTMPose:重新定义多人姿态估计的“实时”标准!
深度学习·算法·计算机视觉
爱喝茶的小茶2 小时前
周赛98补题
开发语言·c++·算法