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 + ``` 使用栈来模拟后序遍历依然可以