【Leetcode_总结】111. 二叉树的最小深度 - python

Q:

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.


链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/

思路:看到这个题目就想起了最大深度 —》 【Leetcode_总结】104. 二叉树的最大深度 - python 当时试试将最大深度的max替换成min 就会出问题,最大那个问题中,递归的终止条件是某一叶子节点不存在,也就是左叶子或右叶子不存在时,就返回1,但是这个题目的话,当根节点的叶子节点不存在时,另外一个分支依旧是有效深度,因此我们需要考虑:

  • 当根节点为空时,返回0
  • 左叶子节点为空时,统计右叶子节点深度
  • 右叶子节点为空时,统计左叶子节点深度
  • 非叶子节点为空时,取左右最小

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if  not root.right:
            return self.minDepth(root.left) + 1
        if not root.left:
            return self.minDepth(root.right) + 1
        return min(self.minDepth(root.left) + 1, self.minDepth(root.right) + 1)

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86072551