BFS模板的应用。
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
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
res = 1
# BFS
stack = [root]
while stack:
lenstack = len(stack)
for i in range(lenstack):
node = stack.pop(0)
if not node.left and not node.right:
return res
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res += 1
return res