描述
给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
样例 1:
输入:
tree = {1,2,3}
输出:
[[2,3],[1]]
解释:
1
/ \
2 3
它将被序列化为 {1,2,3}
样例 2:
输入:
tree = {3,9,20,#,#,15,7}
输出:
[[15,7],[9,20],[3]]
解释:
3
/ \
9 20
/ \
15 7
它将被序列化为 {3,9,20,#,#,15,7}
二叉树的层次遍历肯定是用队列来做,这一题需要把每一层都单独做一个列表,所以需要多一个for循环。同时因为这一题的要求是从叶子到根结点,所以在最后需要通过一个栈来实现。
代码:
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: A tree
@return: buttom-up level order a list of lists of integer
"""
def levelOrderBottom(self, root):
# write your code here
if root is None:
return []
from queue import Queue
q=Queue()
q.put(root)
result_all=[]
while not q.empty():
size=q.qsize()
result=[]
for i in range(size):
node=q.get()
result.append(node.val)
if node.left is not None:
q.put(node.left)
if node.right is not None:
q.put(node.right)
result_all.append(result)
# 栈实现倒装
result_all2=[]
length=len(result_all)
for j in range(length):
result_all2.append(result_all.pop())
return result_all2
Tree = TreeNode(1)
Tree.left = TreeNode(2)
Tree.left.right = TreeNode(5)
Tree.right = TreeNode(3)
s = Solution()
print(s.levelOrderBottom(Tree))