LeetCode107. 二叉树的层次遍历 II
1.题目
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
2.示例
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
3.思路
一个一个加
4.代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return None
answer = []
cur = [root]
while cur:
cur_arr = []
next_cur = []
for node in cur:
if node:
cur_arr.append(node.val)
next_cur.extend([node.left, node.right])
if cur_arr:
answer.insert(0, cur_arr)
cur = next_cur
return answer
5.效果
执行用时 :36 ms, 在所有 python 提交中击败了9.70%的用户
内存消耗 :12.2 MB, 在所有 python 提交中击败了20.12%的用户