[LeetCode]题解(python):107 Binary Tree Level Order Traversal II

Posted loadofleaf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[LeetCode]题解(python):107 Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

《LeetCode之每日一题》:107.最长递增子序列

LeetCode第107题—二叉树的层序遍历II—Python实现

[LeetCode]题解(python):100 Same Tree

[LeetCode]题解(python):112 Path Sum

[LeetCode]题解(python):133-Clone Graph

LeetCode 107