解题思路
广度优先遍历
在节点没有孩子节点的时候就是末梢,这时深度最小的叶子结点,直接返回
111. 二叉树的最小深度
代码
# 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 not root: return 0
queue = [(root, 1)]
while queue:
node, depth = queue.pop(0)
if not node.left and not node.right:
return depth
else:
if node.left:
queue.append((node.left, depth+1))
if node.right:
queue.append((node.right, depth+1))

网友评论