21.leetcode111_minimum_depth_of_binary_tree

1.题目描述

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

给出一个二叉树,返回它的最小深度

2.题目分析

做这个题真的让人有点绝望,因为不断的试错之后才明白什么叫“最小深度”,与求“最大深度”有点不同。这个必须考虑的是节点的两个子节点都没有,而不是考虑当前节点是否存在。

3.解题思路

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 class Solution(object):
 8     def minDepth(self, root):
 9         """
10         :type root: TreeNode
11         :rtype: int
12         """
13         if root==None: #空链表,返回0
14             return 0
15         elif root.left==None and root.right==None: #两个子节点都为空,返回1
16             return 1
17         elif root.left!=None and root.right!=None: #子节点都存在,返回左右节点中的最小深度
18             return min(self.minDepth(root.left)+1,self.minDepth(root.right)+1)#深度+1
19         else: #假如只存在一个节点,返回单节点以下的长度
20             if root.left!=None:
21                 return self.minDepth(root.left)+1 
22             else:
23                 return self.minDepth(root.right)+1
原文地址:https://www.cnblogs.com/19991201xiao/p/8439918.html