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)

相关推荐
√尖尖角↑2 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer2 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
百锦再4 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
碳基学AI5 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3645 小时前
每日算法-250410
算法
袖清暮雨5 小时前
Python刷题笔记
笔记·python·算法
熬夜造bug6 小时前
LeetCode Hot100 刷题笔记(1)—— 哈希、双指针、滑动窗口
笔记·leetcode·hot100
风掣长空6 小时前
八大排序——c++版
数据结构·算法·排序算法
流星白龙7 小时前
【C++算法】50.分治_归并_翻转对
c++·算法
Java致死8 小时前
费马小定理
算法·费马小定理