You are given the root of a binary tree. Return its values grouped by level, but with the reading direction alternating between levels.
The first level is read left to right, the second level right to left, the third left to right again, and so on in a zigzag pattern. The output is a list of lists, one per level, in top-to-bottom order.
The traversal order of the tree does not change; only the direction in which each level's collected values are written out flips from one level to the next.
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Level 0 reads left to right as [3]. Level 1 flips to right to left, giving [20,9]. Level 2 flips back, giving [15,7].
Example 2
Input: root = [1,2,3,4,5]
Output: [[1],[3,2],[4,5]]
The root level is [1]; the next level reversed is [3,2]; the third level returns to left-to-right as [4,5].
Constraints
The number of nodes in the tree is in the range [0, 2000].-1000 <= Node.val <= 1000See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI