Concise python DFS solution(48ms)


  • 0
    H
    from collections import defaultdict
    
    def dfs(node, n, store):
        if not node:
            return
        store[n].append(node.val)
        dfs(node.left, n+1, store)
        dfs(node.right, n+1, store)
    
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            store = defaultdict(list)
            dfs(root, 0, store)
            return [l for _, l in sorted(store.iteritems())]
    

Log in to reply
 

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