mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0104.二叉树的最大深度.md
This commit is contained in:
@ -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
|
||||
|
||||
```
|
||||
|
||||
使用栈来模拟后序遍历依然可以
|
||||
|
Reference in New Issue
Block a user