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

题目来源:

  https://leetcode.com/problems/binary-tree-level-order-traversal-ii/


 

题意分析:

  从底向上宽度遍历二叉树。


 

题目思路:

  自顶向下遍历二叉树后将答案翻转。


 

代码(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 levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ans = []
        def bfs(root,level):
            if root != None:
                if len(ans) < level + 1:
                    ans.append([])
                ans[level].append(root.val)
                bfs(root.left,level + 1)
                bfs(root.right,level + 1)
        bfs(root,0)
        ans.reverse()
        return ans
View Code

 

posted @ 2016-03-09 15:08  Ry_Chen  阅读(617)  评论(0编辑  收藏  举报