问题描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [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).
1 class Solution(object): 2 def levelOrderBottom(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[List[int]] 6 """ 7 if not root: 8 return [] 9 if not root.left and not root.right: 10 return [[root.val]] 11 rear = -1 12 last = 0 13 front = -1 14 b_list = [] 15 temp_list =[] 16 res_list = [] 17 rear += 1 18 b_list.append(root) 19 res_list.append([root.val]) 20 while front < rear: 21 22 front += 1 23 p =b_list.pop(0) 24 if p.left : 25 rear += 1 26 b_list.append(p.left) 27 temp_list.append(p.left.val) 28 if p.right : 29 rear += 1 30 b_list.append(p.right) 31 temp_list.append(p.right.val) 32 if last == front: 33 res_list.append(temp_list) 34 last = rear 35 temp_list = [] 36 res_list.pop() 37 res_list = res_list[::-1] 38 return res_list
简洁版:
1 class Solution(object): 2 def levelOrderBottom(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: List[List[int]] 6 """ 7 if not root:return [] 8 s = [root] 9 res=[] 10 while s: 11 l=[] 12 for i in range(len(s)): 13 n = s.pop(0) 14 l.append(n.val) 15 if n.left: 16 s.append(n.left) 17 if n.right: 18 s.append(n.right) 19 res.append(l) 20 return res[::-1]
2018-09-09 15:10:44