LeetCode 107. 二叉树的层次遍历 II (Python3)
题目描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
语言:
python 3
思路:
分层打印树,将输出列表颠倒
程序:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
currentLevel=[root]
res=[]
while currentLevel:
res.append([c.val for c in currentLevel])
nextLevel=[]
for i in currentLevel:
if i.left:
nextLevel.append(i.left)
if i.right:
nextLevel.append(i.right)
currentLevel=nextLevel
res.reverse()
return res