v9.1.1
Menu

Binary Tree Zigzag Level Order

mediumFREETrees & GraphsMicrosoft DSA

Given a binary tree (level-order array), return the zigzag level order traversal: first level left-to-right, second right-to-left, alternating.

Output each level on a separate line, space-separated.

Example

Input
3,9,20,null,null,15,7
Output
3
20 9
15 7
Reasoning
  • The binary tree is constructed from the level-order array: 3 is the root, 9 and 20 are its children, and 15 and 7 are children of 20.
  • The first level (root) is traversed left-to-right, resulting in the output: 3
  • The second level (9 and 20) is traversed right-to-left, resulting in the output: 20 9
  • The third level (15 and 7) is traversed left-to-right, resulting in the output: 15 7

Constraints

  • 0 <= number of nodes <= 2000

Learn this in

More from Microsoft DSA

solution.py

Test results

Sign in to run your code against the test cases.