Python faster solution: Two queue without reverse


  • 0
    Z

    In python, "To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends"

           def zigzagLevelOrder(self, root):
                ret=[]
                level=0
                queue=collections.deque([root])
                while queue:
                    ret.append(collections.deque())
                    for i in range(len(queue)):
                        node=queue.popleft()
                        if node:
                            if level%2==0: 
                                ret[level].append(node.val)
                            else:
                                ret[level].appendleft(node.val)
                            queue.append(node.left)
                            queue.append(node.right)
                    level+=1
                return [list(x) for x in ret if x]

Log in to reply
 

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