Iterative solution with deque

  • -1
    class Solution(object):
        def zigzagLevelOrder(self, root):
            if not root:
                return []
            stack, r, level = collections.deque([root]), [], 1
            while stack:
                row = []
                for _ in xrange(len(stack)):
                    pop, append = (
                        (stack.pop, stack.appendleft) if level & 1 else
                        (stack.popleft, stack.append))
                    top = pop()
                    [append(c) for c in ((top.left, top.right)
                     if level & 1 else (top.right, top.left)) if c]
                level += 1
            return r

Log in to reply

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