Binary Tree Zigzag Level Order Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.

The traversal should alternate directions by level:

  • Left to right for the first level.
  • Right to left for the next level.
  • Continue alternating between directions for each subsequent level.
Example 1
        3
       / \
      9   20
         /  \
        15   7
Inputroot = [3,9,20,null,null,15,7]
Output[[3],[20,9],[15,7]]
The root level is traversed left to right as [3], the next level right to left as [20, 9], and the final level left to right as [15, 7].
Example 2
        1
Inputroot = [1]
Output[[1]]
The tree has only one node, so the traversal contains a single level with value 1.

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Asked at 19 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate