Leetcode 111:二叉树的最小深度(最详细的解法!!!)
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
1
2
3
4
5
返回它的最小深度 2.
解题思路
这个问题和Leetcode 104:二叉树的最大深度(最详细的解法!!!)很像,我们是不是只要将max换成min就可以了呢?
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return 0 if not root else min(self.minDepth(root.left), self.minDepth(root.right)) + 1
1
2
3
4
5
6
7
当我们碰到这样一个问题的时候
1
/
2
1
2
3
我们只是简单的替换为min就会出错,返回的结果是1。为什么?我们在之前问题中的递归终止条件不适合这个问题,我们错误地将左孩子为空 || 右孩子为空这种情况放到了叶子节点中考虑(也就是错误地将1看成了叶子节点),正确的写法应该是这样的
根节点为空
左孩子为空
右孩子为空
非叶子节点
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
其实如果你思考的足够深入的话,这里可以这样写
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left or not root.right:
return max(self.minDepth(root.right), self.minDepth(root.left)) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
1
2
3
4
5
6
7
8
9
10
11
12
13
同样的,对于可以用递归解决的问题,我们都应该思考一下怎么可以通过迭代去解决,而且对于这个问题迭代解决应该更好理解。那这个问题怎么通过迭代解决呢?那么我们就会用到stack,通过stack模拟上面的递归过程。一个较为简单的思路就是二叉树的层序遍历,参看这篇Leetcode 102:二叉树的层次遍历(最详细解决方案!!!) ,我们在此基础上稍加修改就可以了。
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = float('inf')
if not root:
return 0
q= [(root, 1)]
while stack:
node, depth = q.pop(0)
if not node.left and not node.right:# 叶子节点
result = min(result, depth)
if node.left:
q.append((node.left, depth + 1))
if node.right:
q.append((node.right, depth + 1))
return result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!
---------------------
作者:coordinate_blog
来源:CSDN
原文:https://blog.csdn.net/qq_17550379/article/details/81587912
版权声明:本文为博主原创文章,转载请附上博文链接!

浙公网安备 33010602011771号