Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
LeetCode:链接
其实我觉得这道题和LeetCode102:Binary Tree Level Order Traversal是一样的,只不过用insert插入结果。
# 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 == None:
return []
curStack = [root]
result = []
while curStack:
'''打印当前行'''
res = []
'''存储下一行'''
nextStack = []
for i in curStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
result.insert(0, res)
'''将存储的下一行直接赋值给新的要遍历的内容
也可以用pop 然后直接添加到curStack中'''
curStack = nextStack
return result