力扣刷题-二叉树-二叉树最小深度

给定一个二叉树,找出其最小深度。

最小深度是从根节点最近叶子节点 的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。(注意题意)

示例 1:

输入:root = [3,9,20,null,null,15,7]

输出:2

层序遍历法
python 复制代码
# 层序遍历法
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        queue = deque([(root, 1)]) # 每个元素是元组 一个是树元素值 一个是最小深度 比较巧妙

        while queue:
            cur, min_depth = queue.popleft()
            if not cur.left and not cur.right:
                return min_depth
            if cur.left:
                queue.append((cur.left, min_depth+1))
            if cur.right:
                queue.append((cur.right, min_depth+1))
        return 0

时间复杂度:O(N) 因为每个结点会访问一次

空间复杂度:O(N)在层序遍历法中空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。

递归法

注意这块和最大深度不一样,如下是错误代码:说明:叶子节点是指没有子节点的节点。(注意题意)

这个代码就犯了此图中的误区:说明:叶子节点是指没有子节点的节点。(注意题意)

如果这么求的话,没有左孩子的分支会算为最短深度。

所以,如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。

反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

python 复制代码
# 递归法
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.getDepth(root)
    
    def getDepth(self, node):
        if node is None:
            return 0
        leftDepth = self.getDepth(node.left)  # 左
        rightDepth = self.getDepth(node.right)  # 右
        # 中
        # 当一个左子树为空,右不为空,这时并不是最低点
        if node.left is None and node.right is not None:
            return 1 + rightDepth
        
        # 当一个右子树为空,左不为空,这时并不是最低点
        if node.left is not None and node.right is None:
            return 1 + leftDepth
        
        result = 1 + min(leftDepth, rightDepth)
        return result

时间复杂度:O(N),其中 N 是树的节点数。对每个节点访问一次。

空间复杂度:O(N)/O(H) 其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(log⁡N)

参考:
https://www.programmercarl.com/0111.二叉树的最小深度.html

相关推荐
CQ_YM20 小时前
数据结构之单向链表
c语言·数据结构·链表
gihigo199821 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia21 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia21 小时前
go(基础08)——多态
算法·golang
leoufung21 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
ID_1800790547321 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
Q_Q5110082851 天前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
我是哈哈hh1 天前
【Python数据分析】Numpy总结
开发语言·python·数据挖掘·数据分析·numpy·python数据分析
Michelle80231 天前
24大数据 14-2 函数练习
开发语言·python
qq_381454991 天前
Python学习技巧
开发语言·python·学习