栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

二叉树的最小深度 (Python)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的最小深度 (Python)

LeetCode链接

BFS
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root: return 0
        dq = collections.deque()
        dq.append(root)
        depth = 0
        while dq:
            depth += 1
            for _ in range(len(dq)):
                tmp = dq.popleft()
                # 遇到一个叶子节点就立马返回高度 没必要再往下了
                if not tmp.left and not tmp.right:
                    return depth
                if tmp.left:
                    dq.append(tmp.left)
                if tmp.right:
                    dq.append(tmp.right)
DFS
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        minLeft = self.minDepth(root.left)
        minRight = self.minDepth(root.right)
        # 此处需要注意
        # 1、 只有当两边都有子节点时,最小高度才为两边节点最小高度 + 1
        # 2、当有一侧没有子节点时,最小高度为 另一侧节点的最小高度 + 1  此时  minLeft + minRight + 1 中 minLeft minRight 必有一个为0 所以可直接相加
        return minLeft + minRight + 1 if root.left is None or root.right is None else min(minLeft, minRight) + 1
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/958146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号