mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0104.二叉树的最大深度.md
This commit is contained in:
@ -467,22 +467,31 @@ class Solution:
|
|||||||
|
|
||||||
迭代法:
|
迭代法:
|
||||||
```python
|
```python
|
||||||
import collections
|
"""
|
||||||
class solution:
|
# Definition for a Node.
|
||||||
def maxdepth(self, root: 'node') -> int:
|
class Node:
|
||||||
queue = collections.deque()
|
def __init__(self, val=None, children=None):
|
||||||
if root:
|
self.val = val
|
||||||
queue.append(root)
|
self.children = children
|
||||||
depth = 0 #记录深度
|
"""
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
def maxDepth(self, root: TreeNode) -> int:
|
||||||
|
if not root:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
depth = 0
|
||||||
|
queue = collections.deque([root])
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
size = len(queue)
|
|
||||||
depth += 1
|
depth += 1
|
||||||
for i in range(size):
|
for _ in range(len(queue)):
|
||||||
node = queue.popleft()
|
node = queue.popleft()
|
||||||
for j in range(len(node.children)):
|
for child in node.children:
|
||||||
if node.children[j]:
|
queue.append(child)
|
||||||
queue.append(node.children[j])
|
|
||||||
return depth
|
return depth
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
使用栈来模拟后序遍历依然可以
|
使用栈来模拟后序遍历依然可以
|
||||||
|
Reference in New Issue
Block a user