AlgoInsight

DSA problem

Binary Tree Zigzag Level Order Traversal

MediumTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop300AmazonMicrosoftLinkedInBloombergGoogle

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values: the first level is left to right, the second level is right to left, and the direction continues to alternate between levels.

This problem is a small twist on the classic level-order traversal. The structural BFS is identical — we still process the tree level by level using a queue — but the ordering of values within each level must flip between left-to-right and right-to-left as the depth increases.

There are two clean ways to implement the flip. The simplest is to always enqueue children in their natural left-to-right order, collect the level's values into a list, and reverse that list whenever the level index is odd. This costs O(level_size) per reversal but is easy to reason about and to test.

A second approach uses a deque for the per-level container: when the level is left-to-right we push to the back; when it is right-to-left we push to the front. Both approaches run in O(n) total time and O(w) extra space, where w is the maximum width of the tree. We present the deque-based version below because it avoids a separate reverse pass.

Examples

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Explanation: Level 0 left-to-right is [3]. Level 1 right-to-left flips [9,20] into [20,9]. Level 2 left-to-right is [15,7].
Example 2
Input: root = [1]
Output: [[1]]
Explanation: A single-node tree has only one level whose traversal is trivially [1].
Example 3
Input: root = []
Output: []
Explanation: An empty tree has no levels.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderdeque

Browse all DSA problems