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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值