[LeetCode]题解(python):107 Binary Tree Level Order Traversal II
题目来源
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
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).
题意分析
Input: binary tree
Output: list
Conditions:输出每层的集合,注意是反向输出,即最后一层的先输出
题目思路
同I,将res反置即可
AC代码(Python)
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def preorder(self, root, level, res): 10 if root: 11 if len(res) < level + 1: res.append([]) 12 res[level].append(root.val) 13 self.preorder(root.left, level + 1, res) 14 self.preorder(root.right, level + 1, res) 15 def levelOrderBottom(self, root): 16 """ 17 :type root: TreeNode 18 :rtype: List[List[int]] 19 """ 20 res = [] 21 self.preorder(root, 0, res) 22 res.reverse() 23 print res 24 return res