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).
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
[0, 2000]
.-100 <= Node.val <= 100
This problem requires traversing a binary tree level by level, but with an alternating left-to-right and right-to-left order for each level. This is known as a zigzag traversal. The most efficient approach uses Breadth-First Search (BFS).
Initialization: We start with a queue q
containing the root node and an empty result list ans
. A boolean variable left
is initialized to true
, indicating that the first level should be traversed from left to right.
Level-by-Level Traversal: The main loop continues as long as the queue q
is not empty. In each iteration, we process one level of the tree.
Processing a Level: A temporary list t
stores the node values of the current level. We iterate through the current size of the queue. For each node, we:
t
.q
.Zigzag Ordering: After processing a level, we check the value of left
.
left
is true
, the values in t
are already in the correct left-to-right order; we append t
directly to ans
.left
is false
, we reverse t
before appending it to ans
to achieve the right-to-left order.Direction Toggle: We then toggle the value of left
(left = !left
) to switch the direction for the next level.
Return Result: Finally, we return the ans
list containing the zigzag level order traversal.
Time Complexity: The algorithm visits each node in the tree exactly once. Therefore, the time complexity is O(N), where N is the number of nodes in the binary tree.
Space Complexity: In the worst case (a complete binary tree), the queue q
can hold up to O(N/2) ≈ O(N) nodes at any given time. The ans
list also stores at most N values. Therefore, the space complexity is O(N).
The code examples in various programming languages provided in the original response accurately implement this BFS-based approach. The core logic remains consistent across all languages, differing only in syntax and data structure implementations (e.g., queue
, deque
, vector
). Each example includes comments to enhance readability and understanding.