From 61173277185bf7948ffb576212cc31fd383778e3 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:12:16 -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 | 31 ++++++++++++++--------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 89e7a126..13694207 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2664,24 +2664,31 @@ class Solution { Python: ```python 3 +# 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 maxDepth(self, root: TreeNode) -> int: - if root == None: + if not root: return 0 - - queue_ = [root] + depth = 0 - while queue_: - length = len(queue_) - for i in range(length): - cur = queue_.pop(0) - sub.append(cur.val) - #子节点入队列 - if cur.left: queue_.append(cur.left) - if cur.right: queue_.append(cur.right) + queue = collections.deque([root]) + + while queue: depth += 1 - + for _ in range(len(queue)): + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth + ``` Go: