Skip to content
RED SAGSkills
medium30 ptstreebfs

Zigzag Levels of a Tree

A binary tree is given as a level-order array tree with null for missing children (children of a missing node are not listed).

Return the values level by level, where the first level is read left to right, the second right to left, the third left to right again, and so on.

Example 1

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

Example 2

Input: tree = [1,2,3,4,5,6,7]
Output: [[1],[3,2],[4,5,6,7]]

Constraints

  • 0 <= number of nodes <= 2000
  • -100 <= node value <= 100
Hint 1

Do a normal breadth-first traversal, collecting one level at a time.

Hint 2

Reverse every second level before adding it to the result.

Discussion 0

Join free to post in the discussion.

Good practice for: Backend Developer, Frontend Developer, Full Stack Developer, Game Developer, Mobile App Developer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.