Concise python DFS solution(48ms)

  • 0
    from collections import defaultdict
    def dfs(node, n, store):
        if not node:
        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.