AC Python BFS, using deque and dict


  • 0
    from collections import deque
    class Solution(object):
        def levelOrderBottom(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if root == None: return []
            queue = deque([[root, 1]])
            dic = {}
            while queue:
                node, level = queue.popleft()
                if not dic.has_key(level):
                    dic[level] = []
                dic[level].append(node.val)
                if node.left != None:
                    queue.append([node.left, level + 1])
                if node.right != None:
                    queue.append([node.right, level + 1])
            return dic.values()[::-1]
    

Log in to reply
 

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