LeetCode in python 111. 二叉树的最小深度

87 阅读1分钟

1、题目

leetcode.cn/problems/mi…

给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

image.png

2、思考

同104题一样,采用递归的方法,只是不同于求最大深度,最小深度需要考虑下左或者右子树不存在的情况。

3、解题

# 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 root is None:
            return 0
        if not root.right:
            return self.minDepth(root.left)+1
        if not root.left:
            return self.minDepth(root.right)+1
        else:
            return min(self.minDepth(root.left),self.minDepth(root.right))+1

一顿操作猛如虎,一看结果62%。

image.png