Python BFS using queue


  • 0

    Using dic to store the values of each level's nodes in corresponding lists. When return the result, reverse every other level.

    class Solution(object):
        def zigzagLevelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            queue = collections.deque([(root, 0)]) if root else []
            dic = collections.defaultdict(list)
            while queue:
                node, level = queue.popleft()
                dic[level].append(node.val)
                if node.left: queue.append((node.left, level+1))
                if node.right: queue.append((node.right, level+1))
            return [dic[level][::(1, -1)[level & 1]] for level in range(len(dic))]
    

Log in to reply
 

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