From aac7378cb62ed2ec36fc1012f0057844297bda67 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 21:40:49 -0500 Subject: [PATCH] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 25 +++++++++++++++-------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 36578fd3..2294c1d9 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -419,26 +419,33 @@ class solution: return 1 + max(self.maxdepth(root.left), self.maxdepth(root.right)) ``` -迭代法: +层序遍历迭代法: ```python -import collections -class solution: - def maxdepth(self, root: treenode) -> int: +# 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 not root: return 0 - depth = 0 #记录深度 - queue = collections.deque() - queue.append(root) + + depth = 0 + queue = collections.deque([root]) + while queue: - size = len(queue) depth += 1 - for i in range(size): + for _ in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) + return depth + ``` ### 559.n叉树的最大深度