MediumTreeBreadth-First SearchBinary Tree

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Relay Tower Snake Sweep is our own problem on the technique behind Binary Tree Zigzag Level Order Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free