AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Binary Tree Zigzag Level Order Traversal

The key idea

Do a normal breadth-first level-order traversal, but flip the direction every level. Collect each level left to right as usual, then reverse the even-indexed levels (or reverse on alternate levels) so the output zigzags.

Problem

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).

Constraints

Examples

Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]
Input: root = [1] Output: [[1]]
Input: root = [] Output: []

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems