算法思想:
BFS问题的本质就是让你在一幅「图」中找到从起点start到终点target的最近距离(最短路径)。
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode):
if not root:
return 0
step = 1
q = [root]
while q:
for i in range(len(q)):
tmp = q.pop(0)
if not tmp.left and not tmp.right:
return step
if tmp.left:
q.append(tmp.left)
if tmp.right:
q.append(tmp.right)
step += 1
return step