From 75d137eb1c0464de0321f611ed66125e322936e7 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 00:23:53 -0500 Subject: [PATCH] =?UTF-8?q?Update=200111.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 59 +++++++++++++++-------- 1 file changed, 39 insertions(+), 20 deletions(-) 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 ```