mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
优化 0102.二叉树的层序遍历.md Python3解法
任何在 list 头部进行的操作都会损失一定性能 在 Python 中应该使用 collections.deque 作为队列的数据类型 在该数据类型左右两端追加和弹出元素的时间复杂度都接近O(1)
This commit is contained in:
@ -87,26 +87,31 @@ public:
|
|||||||
|
|
||||||
python代码:
|
python代码:
|
||||||
|
|
||||||
```python
|
```python3
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树层序遍历迭代解法"""
|
||||||
|
|
||||||
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
||||||
|
results = []
|
||||||
if not root:
|
if not root:
|
||||||
return []
|
return results
|
||||||
|
|
||||||
|
from collections import deque
|
||||||
|
que = deque([root])
|
||||||
|
|
||||||
|
while que:
|
||||||
|
size = len(que)
|
||||||
|
result = []
|
||||||
|
for _ in range(size):
|
||||||
|
cur = que.popleft()
|
||||||
|
result.append(cur.val)
|
||||||
|
if cur.left:
|
||||||
|
que.append(cur.left)
|
||||||
|
if cur.right:
|
||||||
|
que.append(cur.right)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
queue = [root]
|
return results
|
||||||
out_list = []
|
|
||||||
|
|
||||||
while queue:
|
|
||||||
length = len(queue)
|
|
||||||
in_list = []
|
|
||||||
for _ in range(length):
|
|
||||||
curnode = queue.pop(0) # (默认移除列表最后一个元素)这里需要移除队列最头上的那个
|
|
||||||
in_list.append(curnode.val)
|
|
||||||
if curnode.left: queue.append(curnode.left)
|
|
||||||
if curnode.right: queue.append(curnode.right)
|
|
||||||
out_list.append(in_list)
|
|
||||||
|
|
||||||
return out_list
|
|
||||||
```
|
```
|
||||||
|
|
||||||
java:
|
java:
|
||||||
|
Reference in New Issue
Block a user