MediumPythonJavaScriptTypeScript
Binary Tree — Zigzag Level Order
Data StructuresTreesBFSQueue
Return the level-order traversal of a binary tree, but alternate the direction on
each level: left → right on the first level, right → left on the second,
then left → right again, and so on.
solve(levelOrder) receives the tree serialized level by level and returns an
array of arrays (one per level). An empty tree returns [].
Examples
solve([3, 9, 20, null, null, 15, 7]) → [[3], [20, 9], [15, 7]]
solve([1, 2, 3, 4, 5, 6, 7]) → [[1], [3, 2], [4, 5, 6, 7]]
solve([1]) → [[1]]
solve([]) → []Keep the BFS itself in normal left-to-right order — only the output of every
other level is reversed.
Sample tests
Test #1Classic example
Input: [[3,9,20,null,null,15,7]]
Output: [[3],[20,9],[15,7]]
Test #2Single node
Input: [[1]]
Output: [[1]]
Test #3Empty tree
Input: [[]]
Output: []