diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index de36c6f2..bda12ff0 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -300,44 +300,63 @@ class Solution { 递归法: ```python +# 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: TreeNode) -> int: if not root: return 0 + if not root.left and not root.right: return 1 - - min_depth = 10**9 + + left_depth = float('inf') + right_depth = float('inf') + if root.left: - min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 + left_depth = self.minDepth(root.left) if root.right: - min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 - return min_depth + 1 + right_depth = self.minDepth(root.right) + + return 1 + min(left_depth, right_depth) + ``` 迭代法: ```python +# 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: TreeNode) -> int: if not root: return 0 - que = deque() - que.append(root) - res = 1 - - while que: - for _ in range(len(que)): - node = que.popleft() - # 当左右孩子都为空的时候,说明是最低点的一层了,退出 + depth = 0 + queue = collections.deque([root]) + + while queue: + depth += 1 + for _ in range(len(queue)): + node = queue.popleft() + if not node.left and not node.right: - return res - if node.left is not None: - que.append(node.left) - if node.right is not None: - que.append(node.right) - res += 1 - return res + return depth + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) + + return depth ```