LeetCode111-二叉树的最小深度-Python3

题目

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

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

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

示例:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

思路

采用递归实现

递归有以下几种情况: 
1.根节点为空,深度为0 
2.只有一个根节点。深度为1 
3.左右子树皆不空,则返回1+左右子树中最小的深度。 
4.左子树不为空,则返回1+左子树深度。这里可以想象成只有根节点a,以及其左子树b,此时最小深度为2。 
5.右子树不为空,则返回1+右子树深度。同上。 

Python3代码

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def minDepth(self, root):
        if root:
            if root.left and root.right:
                return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
            elif root.left:
                return 1 + self.minDepth(root.left)
            elif root.right:
                return 1 + self.minDepth(root.right)
            else:
                return 1
        else:
            return 0

猜你喜欢

转载自blog.csdn.net/weixin_42762089/article/details/86914743