Example 1
- Input
- root = [3,9,20,null,null,15,7]
- Output
- [[3],[20,9],[15,7]]
Level 0 gives [3], level 1 is reversed to [20,9], and level 2 stays [15,7].
Given the root of a binary tree, return its values level by level while alternating direction on every level: even levels run left to right and odd levels run right to left. An empty tree returns an empty list.
Given the root of a binary tree, return the zigzag level order traversal of its node values.
Level 0 is read left to right, level 1 is read right to left, level 2 is read left to right again, and the direction keeps alternating. Return one list per level, or an empty list when root is null.
Level 0 gives [3], level 1 is reversed to [20,9], and level 2 stays [15,7].
A single node forms one level read left to right.
An empty tree has no levels, so the answer is an empty list.
Reverse the second level to [3,2], but keep discovering children through parents 2 then 3. This makes the third level [4,5,6], rather than [5,6,4]. Missing children do not add output placeholders.
Separate which nodes belong to a depth from which direction their values are displayed. A queue discovers each depth left to right; only the output changes direction. In Example 1, visit 9 before 20 to discover their children correctly, but display that level as [20,9]. The next level still displays [15,7].
Reveal BFS Then Reverse: intuition, complexity, and code
Level-order problems are breadth-first searches with per-level bookkeeping, so a small flag or index tweak adapts the same traversal to zigzag orders, averages, and side views.