111. Minimum Depth of Binary Tree
一看就是BFS,搜到left/right child 都是 null 的时候就返回当前深度。
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
res = 0
queue = collections.deque([root])
while queue:
res += 1
n_ = len(queue)
for i in range(n_):
node = queue.popleft()
if not node.left and not node.right:
return res
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
Last updated
Was this helpful?