Minimum Depth of Binary Tree
题目:难度(Easy)
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.
Tags:Tree, Depth-first Search ,Breadth-first Search
法1:DFS
分析:此题不能直接套用Maximum Depth of Binary Tree的方法直接使用depthMin = min(leftMinDepth, rightMinDepth)+1。因为像单支树这样的树,按题意它的深度应该是子树的深度+1,而不是0。
代码实现:
<span style="font-size:14px;"># 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):
#DFS
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right))+1
elif root.left:
return self.minDepth(root.left)+1
else:
return self.minDepth(root.right)+1</span>
法2:BFS
分析:找到的第一个叶子节点所在的高度就是该树的最小深度。
代码实现:
<span style="font-size:14px;"># 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
"""
if root is None:
return 0
from collections import deque
queue = deque()
queue.append(root)
curNodesNumEachLevel = 1
depthMin = 1
while queue:
frontElem = queue.popleft()
curNodesNumEachLevel -= 1
#注意:判断是否是叶子节点的条件语句必须放在depthMin += 1的前面
#只有在某一层的全部节点考察完后深度才会加1,而在curNodesNumEachLevel=0之前,就可能先出现了叶子节点(在该层上)
if frontElem.left is None and frontElem.right is None:#找到叶子节点
break
if frontElem.left:
queue.append(frontElem.left)
if frontElem.right:
queue.append(frontElem.right)
if curNodesNumEachLevel == 0:
#上一层的节点都出队了,深度增加,到这一层
depthMin += 1
curNodesNumEachLevel = len(queue)
return depthMin</span>