呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 107 Binary Tree Level Order Traversal II

文档信息

leetcode 107 Binary Tree Level Order Traversal II

解法一

# 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]]
        """
        self.ans = list()
        def dfs(root, level = 0):
            if root:
                if len(self.ans) <= level:
                    self.ans.append(list())
                self.ans[level].append(root.val)
                
                if root.left: dfs(root.left, level+1)
                if root.right: dfs(root.right, level+1)
        
        dfs(root)
        return self.ans[::-1]

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub