1 """ 2 Given a binary tree, find its minimum depth. 3 The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 4 Note: A leaf is a node with no children. 5 Example: 6 Given binary tree [3,9,20,null,null,15,7], 7 3 8 / 9 9 20 10 / 11 15 7 12 return its minimum depth = 2. 13 """ 14 """ 15 解法一:迭代,用一个(node,depth) 与树结构绑定 并持续更新 16 """ 17 class TreeNode: 18 def __init__(self, x): 19 self.val = x 20 self.left = None 21 self.right = None 22 23 class Solution1: 24 def minDepth(self, root): 25 if not root: 26 return 0 27 queue = [] 28 queue.append((root, 1)) #!!!关键记录深度 29 res = float('inf') #结果初始化为最大 30 while queue: 31 node, depth = queue.pop(0) 32 if not node.left and not node.right: 33 res = min(res, depth) 34 if node.left: 35 queue.append((node.left, depth+1)) 36 if node.right: 37 queue.append((node.right, depth+1)) 38 return res 39 """ 40 解法二:递归 41 """ 42 class Solution2: 43 def minDepth(self, root): 44 if not root: 45 return 0 46 if not root.left: 47 return self.minDepth(root.right)+1 48 if not root.right: 49 return self.minDepth(root.left)+1 50 return min(self.minDepth(root.left), self.minDepth(root.right))+1