Python solution using deque and defaultdict

  • 2
    def levelOrderBottom(self, root):
        :type root: TreeNode
        :rtype: List[List[int]]
        if not root:
            return []
        levels = defaultdict(list)
        queue = deque([(root, 1)])
        while len(queue):
            current, depth = queue.popleft()
            if current.left:
                queue.append((current.left, depth+1))
            if current.right:
                queue.append((current.right, depth+1))
        n = len(levels)
        return [levels[i] for i in xrange(n, -1, -1) if levels[i]]

Log in to reply

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