题目来源
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)
# 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 preorder(self, root, level, res):
if root:
if len(res) < level + 1: res.append([])
res[level].append(root.val)
self.preorder(root.left, level + 1, res)
self.preorder(root.right, level + 1, res)
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.preorder(root, 0, res)
res.reverse()
print res
return res