小黑代码
# 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: Optional[TreeNode]) -> int: if not root: return 0 depth = 0 # 初始化队列 q = collections.deque([root]) # 层次便利 while q: depth += 1 # 记录该层有多少元素 n = len(q) # 遍历每一个结点 for _ in range(n): top = q.popleft() if top.left: q.append(top.left) if top.right: q.append(top.right) # 叶子结点 if not (top.left or top.right): return depth return -1
1234567891011121314151617181920212223242526272829深度优先
# 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: Optional[TreeNode]) -> int: if not root: return 0 if not (root.left or root.right): return 1 min_depth = float('inf') # 取左右子树最小值 if root.left: min_depth = min(min_depth, self.minDepth(root.left)) if root.right: min_depth = min(min_depth, self.minDepth(root.right)) return min_depth + 1
12345678910111213141516171819层次便利
# 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: Optional[TreeNode]) -> int: if not root: return 0 # 初始化队列,记录深度 q = collections.deque([(root, 1)]) # 层次遍历 while q: top = q.popleft() node, depth = top if node.left: q.append((node.left, depth + 1)) if node.right: q.append((node.right, depth + 1)) # 发现最浅叶子结点 if not (node.left or node.right): return depth return -1
123456789101112131415161718192021222324小黑生活
被阿黄放了鸽子啦,真是个好男人
从家骑到朝阳公园准备享受一番
跟justRUN一起慢跑享受
生活要有仪式感,来杯喜茶