# Definition for a binary tree node.classTreeNode:def__init__(self, x):
self.val = x
self.left =None
self.right =NoneclassSolution:defminDepth(self, root: TreeNode)->int:ifnot root:return0
q =[]
q.append(root)
ans =1while q:
tmp =[]for i in q:if i.left:
tmp.append(i.left)if i.right:
tmp.append(i.right)ifnot i.left andnot i.right:return ans
ans +=1
q = tmp
return ans
递归
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defminDepth(self, root: TreeNode)->int:ifnot root:return0
l = self.minDepth(root.left)+1
r = self.minDepth(root.right)+1if root.left and root.right:returnmin(l, r)elif root.left:return l
else:return r