首页 > 编程语言 > 详细

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

时间:2016-03-09 15:51:55      阅读:325      评论:0      收藏:0      [点我收藏+]

题目来源:

  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

 

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

原文:http://www.cnblogs.com/chruny/p/5258262.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!