Problem Statement in English

You’re given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).


Approach

We need to add a little flag to a standard level order traversal.

We can use a queue to traverse the tree level by level. For each level, we can check the flag to determine whether to append the values from left to right or from right to left.

After processing each level, we toggle the flag for the next level.

And we’re done!


Solution in Python



class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []

        lrmode = True

        temp = [root]
        ans = []

        while temp:
            q = deque(temp)
            temp = []
            buffer = []

            while q:
                node=q.popleft()
                buffer.append(node.val)

                if node.left:
                    temp.append(node.left)
                if node.right:
                    temp.append(node.right)

            if not lrmode:
                buffer.reverse()
            ans.append(buffer)
            lrmode = not lrmode

        return ans

Complexity

  • Time: $O(n)$
    Since we are traversing all the nodes of the tree, the time complexity is linear with respect to the number of nodes in the tree.

  • Space: $O(n)$
    Since we are storing the nodes of the tree in a queue, the space complexity is also linear with respect to the number of nodes in the tree.


And we are done.