From de7c67c35a5d3d0e423072d0b7cb02876c628786 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:13:38 -0500 Subject: [PATCH] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 33 ++++++++++++----------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 13694207..c2ad9508 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2938,23 +2938,26 @@ Python 3: # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: - if root == None: + if not root: return 0 + 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 depth + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) - #根节点的深度为1 - queue_ = [(root,1)] - while queue_: - cur, depth = queue_.pop(0) - - if cur.left == None and cur.right == None: - return depth - #先左子节点,由于左子节点没有孩子,则就是这一层了 - if cur.left: - queue_.append((cur.left,depth + 1)) - if cur.right: - queue_.append((cur.right,depth + 1)) - - return 0 + return depth ``` Go: