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

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

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

示例 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

相关推荐
snowfoootball21 分钟前
最短路问题
数据结构·算法
怀旧,1 小时前
【数据结构】4.单链表实现通讯录
android·服务器·数据结构
有你的冬天1981 小时前
数据结构(一)
数据结构·算法
满怀10152 小时前
【Python进阶】列表:全面解析与实战指南
python·算法
purrrew2 小时前
【数据结构_9】栈和队列
数据结构
爱学习的uu2 小时前
决策树:ID3,C4.5,CART树总结
算法·决策树·机器学习
wuqingshun3141592 小时前
蓝桥杯 9. 九宫幻方
数据结构·c++·算法·职场和发展·蓝桥杯·深度优先
小小菜鸟,可笑可笑2 小时前
Python 注释进阶之Google风格
开发语言·python
upp2 小时前
[bug]langchain agent报错Invalid Format: Missing ‘Action Input:‘ after ‘Action:‘
javascript·python·langchain·bug
小技与小术2 小时前
代码随想录算法训练营day4(链表)
数据结构·python·算法·链表