easy to understand recursive DFS in python 52ms


  • 0
    L
    class Solution(object):
        def levelOrderBottom(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            d = {}
            dfs(root, d)
            maxl = max([k for k in d])
            return [d[i] for i in range(maxl, -1, -1)]
            
    
    def dfs(node, d={}, level=0):
        d.setdefault(level, [])
        try:
            d[level].append(node.val)
        
            if node.left:
                dfs(node.left, d, level + 1)
            if node.right:
                dfs(node.right, d, level + 1)
        except:
            pass
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.