Ctrl K

Snake Through the Tree Levels

Medium
You are given the root of a binary tree. Walk it level by level like a snake: the root's level is read left to right, the next one right to left, the next one left to right again, and so on, alternating the direction. Return the list of levels from top to bottom, each level being the list of values in reading order. For an empty tree, return an empty list.
Example 1
root=tree_node([8, 3, 10, 1, 6, None, 14]) → [[8], [10, 3], [1, 6, 14]]

Level 0 is read left to right: 8. Level 1 right to left: 10, 3. Level 2 left to right again: 1, 6, 14.

Example 2
root=tree_node([1, 2, None, 3, 4]) → [[1], [2], [3, 4]]

Level 1 has a single node, so the direction does not matter; level 2 is left to right again: 3, 4.

Example 3
root=tree_node([]) → []

An empty tree gives an empty list.

Constraints
  • 0 ≤ number of nodes ≤ 2000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Rows by Depth MediumTree Levels From the Bottom Up MediumThe Tree Seen From the Right MediumTree Columns, Top Down MediumFirst Value on the Lowest Row Medium
loading Python…
Input
root=tree_node([8, 3, 10, 1, 6, None, 14])
Expected
[[8], [10, 3], [1, 6, 14]]

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.