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