MediumTreeBreadth-First SearchBinary Tree

Binary Tree Zigzag Level Order Traversal

LeetCode
1 approach, code in all languages

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 <= 1000
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now