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)

相关推荐
MATLAB代码顾问14 分钟前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天18 分钟前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap26 分钟前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿40 分钟前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6671 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-19432 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
智者知已应修善业2 小时前
【51单片机不用数组动态数码管显示字符和LED流水灯】2023-10-3
c++·经验分享·笔记·算法·51单片机
AI进化营-智能译站3 小时前
ROS2 C++开发系列16-智能指针管理传感器句柄|告别ROS2节点内存泄漏与野指针
java·c++·算法·ai
CS创新实验室3 小时前
从盘边到芯端——硬盘接口七十年变迁史
算法·磁盘调度
xvhao20133 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法