Problem statement

https://binarysearch.com/problems/Level-Order-Alternating/

Solution

Variation of 103. Binary Tree Zigzag Level Order Traversal

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, root):
        if not root: return []
        queue = deque([root])
        result, direction = [], 1
        
        while queue:
            level = []
            for i in range(len(queue)):
                node = queue.popleft()
                level.append(node.val)
                if node.left:  queue.append(node.left)
                if node.right: queue.append(node.right)
            result += level[::direction]
            direction *= (-1)
        return result