问题描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
] 方法1:以为二叉树的层次遍历为依托,把该层的值append到temp_list中,当front等于last时,表明当前层遍历结束,res_list.append(temp_list).
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
if not root.left and not root.right:
return [[root.val]]
rear = -1
last = 0
front = -1
b_list = []
temp_list =[]
res_list = []
rear += 1
b_list.append(root)
res_list.append([root.val])
while front < rear: front += 1
p =b_list.pop(0)
if p.left :
rear += 1
b_list.append(p.left)
temp_list.append(p.left.val)
if p.right :
rear += 1
b_list.append(p.right)
temp_list.append(p.right.val)
if last == front:
res_list.append(temp_list)
last = rear
temp_list = []
res_list.pop()
res_list = res_list[::-1]
return res_list
简洁版:
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:return []
s = [root]
res=[]
while s:
l=[]
for i in range(len(s)):
n = s.pop(0)
l.append(n.val)
if n.left:
s.append(n.left)
if n.right:
s.append(n.right)
res.append(l)
return res[::-1]
2018-09-09 15:10:44