Binary Tree Zigzag Level Order Traversal - aloalgo

Binary Tree Zigzag Level Order Traversal

Medium

You are given the root of a binary tree.

Your task is to return the zigzag level order traversal of its nodes' values.

Note that:

  • The traversal should alternate direction for each level: left to right for the first level, right to left for the second, left to right for the third, and so on.

Return the zigzag level order traversal as a list of lists of integers, where each inner list represents a level's values.

Example 1

Input
3920157
Output
[
  [3],
  [20, 9],
  [15, 7]
]
Explanation:

Level 0: [3] (left to right). Level 1: [20,9] (right to left). Level 2: [15,7] (left to right).

Example 2

Input
1
Output
[
  [1]
]
Explanation:

Only one node at level 0 (left to right).

Example 3

Input
None
Output
[
  
]
Explanation:

The tree is empty, so no nodes to traverse.

Example 4

Input
12435
Output
[
  [1],
  [3, 2],
  [4, 5]
]
Explanation:

Level 0: [1] (left to right). Level 1: [3,2] (right to left). Level 2: [4,5] (left to right).

Loading...
Input
3920157
Output
[
  [3],
  [20, 9],
  [15, 7]
]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!