Skip to content

Commit 578e990

Browse files
committed
优化 0102.二叉树的层序遍历.md 中的 429.N叉树的层序遍历 Python3解法
1 parent fde18e8 commit 578e990

File tree

1 file changed

+17
-41
lines changed

1 file changed

+17
-41
lines changed

problems/0102.二叉树的层序遍历.md

Lines changed: 17 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -825,52 +825,28 @@ public:
825825
python代码:
826826

827827
```python
828-
829828
class Solution:
829+
"""N叉树的层序遍历迭代法"""
830+
830831
def levelOrder(self, root: 'Node') -> List[List[int]]:
832+
results = []
831833
if not root:
832-
return []
834+
return results
833835

834-
quene = deque([root])
835-
out_list = []
836-
837-
while quene:
838-
in_list = []
839-
840-
for _ in range(len(quene)):
841-
node = quene.popleft()
842-
in_list.append(node.val)
843-
if node.children:
844-
# 这个地方要用extend而不是append,我们看下面的例子:
845-
# In [18]: alist=[]
846-
# In [19]: alist.append([1,2,3])
847-
# In [20]: alist
848-
# Out[20]: [[1, 2, 3]]
849-
# In [21]: alist.extend([4,5,6])
850-
# In [22]: alist
851-
# Out[22]: [[1, 2, 3], 4, 5, 6]
852-
# 可以看到extend对要添加的list进行了一个解包操作
853-
# print(root.children),可以得到children是一个包含
854-
# 孩子节点地址的list,我们使用for遍历quene的时候,
855-
# 希望quene是一个单层list,所以要用extend
856-
# 使用extend的情况,如果print(quene),结果是
857-
# deque([<__main__.Node object at 0x7f60763ae0a0>])
858-
# deque([<__main__.Node object at 0x7f607636e6d0>, <__main__.Node object at 0x7f607636e130>, <__main__.Node object at 0x7f607636e310>])
859-
# deque([<__main__.Node object at 0x7f607636e880>, <__main__.Node object at 0x7f607636ef10>])
860-
# 可以看到是单层list
861-
# 如果使用append,print(quene)的结果是
862-
# deque([<__main__.Node object at 0x7f18907530a0>])
863-
# deque([[<__main__.Node object at 0x7f18907136d0>, <__main__.Node object at 0x7f1890713130>, <__main__.Node object at 0x7f1890713310>]])
864-
# 可以看到是两层list,这样for的遍历就会报错
865-
866-
quene.extend(node.children)
867-
868-
out_list.append(in_list)
836+
from collections import deque
837+
que = deque([root])
869838

870-
return out_list
871-
872-
# 执行用时:60 ms, 在所有 Python3 提交中击败了76.99%的用户
873-
# 内存消耗:16.5 MB, 在所有 Python3 提交中击败了89.19%的用户
839+
while que:
840+
result = []
841+
for _ in range(len(que)):
842+
cur = que.popleft()
843+
result.append(cur.val)
844+
# cur.children 是 Node 对象组成的列表,也可能为 None
845+
if cur.children:
846+
que.extend(cur.children)
847+
results.append(result)
848+
849+
return results
874850
```
875851

876852
java:

0 commit comments

Comments
 (0)