Skip to the code
cf.
+25 XP

#327 Alternating Row Order

medium

A kiosk animation reveals a category tree row by row, sweeping like a snake: the first row left to right, the next row right to left, then left to right again.

Write snakeRows(root) that returns the values level by level, where level 0 is read left to right, level 1 right to left, level 2 left to right, and so on. An empty tree returns [].

Example 1

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

Level 1 is read right to left.

Example 2

Input: root = [1,2,null,3,4]
Output: [[1],[2],[3,4]]

A one-node row looks the same both ways.

Constraints

  • 0 <= number of nodes <= 2000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).