Python BFS Solution using deque, easy to understand


  • 0
    Y

    I use deque function to save both node and level, and use dictionary with list type value to save the result.

    class Solution(object):
        def levelOrder(self, root):
            queue=collections.deque([(root,1)])
            dic=collections.defaultdict(list)
            res=[]
            while queue:
                root,level=queue.popleft()
                if not root: continue
                dic[level].append(root.val)
                if root.left:queue.append([root.left,level+1])
                if root.right:queue.append([root.right,level+1])
            for key in sorted(dic):
                res.append(dic[key])
            return res
    

Log in to reply
 

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