From be27cc547daf4c82a048b71f201c93ed3b2b3e2e Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 21:57:13 -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 | 33 ++++++++++++++--------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index c4d94d4d..c55ddb3f 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -467,22 +467,31 @@ class Solution: 迭代法: ```python -import collections -class solution: - def maxdepth(self, root: 'node') -> int: - queue = collections.deque() - if root: - queue.append(root) - depth = 0 #记录深度 +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: + return 0 + + 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() - for j in range(len(node.children)): - if node.children[j]: - queue.append(node.children[j]) + for child in node.children: + queue.append(child) + return depth + ``` 使用栈来模拟后序遍历依然可以