求二叉树最小深度
Day47: 题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
![4ea2d9412fd0d385f3ceb9b08a1a2d34.png](https://i-blog.csdnimg.cn/blog_migrate/732a6bbc6b2afbca0ffc2c00b1077856.png)
给定二叉树 [3,9,20,null,null,15,7],
返回它的最小深度 2.
补全下面代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
2 分析
分析过程的开始,我们先看一个错误的求解,并说明为什么它是错误的:
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right:
return 1
return 1 + min(self.minDepth(root.left),self.minDepth(root.right))
考虑下面二叉树:
![1a6da0bb292a37d040679e1b668edc42.png](https://i-blog.csdnimg.cn/blog_migrate/a8c51b31337d030bc7681936f7d3949f.png)
使用以上代码返回最小深度为 1,其实最小深度为 2,因为最小深度的定义为:从根节点到最近叶子节点的最短路径上的节点数量。
为什么上面的解有问题呢?
原因在于递归基选取有问题,只考虑了下面两种情况:
- 二叉树为 None
- 二叉树只有一个节点
递归基未考虑下面两种情况,所以导致出错:
![175b6ab3cc47349a069078aaee5c4948.png](https://i-blog.csdnimg.cn/blog_migrate/a1f70ede06970dec6444569ad22c555a.png)
3 正确求解
正确的求解,需要把上面遗漏的两种递归基考虑进去:
# 递归基的下面两种情况必须考虑进去:
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
正确的完整代码如下:
class Solution(object):
def minDepth(self, root):
if not root:
return 0
if not root.left and not root.right:
return 1
# 递归基的下面两种情况必须考虑进去:
if not root.left:
return 1 + self.minDepth(root.right)
if not root.right:
return 1 + self.minDepth(root.left)
return 1 + min(self.minDepth(root.left),self.minDepth(root.right))
《end》
欢迎加入星球,从零学程序员必备算法,每天在星球内记录学习过程、学习星友超赞的回答,加入后领取前45天的150页算法刷题日记pdf总结。