mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
优化 0102.二叉树的层序遍历.md 中的 107.二叉树的层次遍历 II Python3解法
This commit is contained in:
@ -279,29 +279,29 @@ python代码:
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树层序遍历II迭代解法"""
|
||||||
|
|
||||||
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
|
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
|
||||||
|
results = []
|
||||||
if not root:
|
if not root:
|
||||||
return []
|
return results
|
||||||
quene = [root]
|
|
||||||
out_list = []
|
|
||||||
|
|
||||||
while quene:
|
from collections import deque
|
||||||
in_list = []
|
que = deque([root])
|
||||||
for _ in range(len(quene)):
|
|
||||||
node = quene.pop(0)
|
|
||||||
in_list.append(node.val)
|
|
||||||
if node.left:
|
|
||||||
quene.append(node.left)
|
|
||||||
if node.right:
|
|
||||||
quene.append(node.right)
|
|
||||||
|
|
||||||
out_list.append(in_list)
|
while que:
|
||||||
|
result = []
|
||||||
|
for _ in range(len(que)):
|
||||||
|
cur = que.popleft()
|
||||||
|
result.append(cur.val)
|
||||||
|
if cur.left:
|
||||||
|
que.append(cur.left)
|
||||||
|
if cur.right:
|
||||||
|
que.append(cur.right)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
out_list.reverse()
|
results.reverse()
|
||||||
return out_list
|
return results
|
||||||
|
|
||||||
# 执行用时:36 ms, 在所有 Python3 提交中击败了92.00%的用户
|
|
||||||
# 内存消耗:15.2 MB, 在所有 Python3 提交中击败了63.76%的用户
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
Reference in New Issue
Block a user