InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Binary Tree Zigzag Level Order Traversal

medium Original ↗ 00:00

Problem

You are given the root of a binary tree. Return the values of its nodes grouped by level (depth), but with the direction alternating: the first level is listed left-to-right, the second level right-to-left, the third left-to-right again, and so on.

The answer is a list of lists — one inner list per level, ordered from the root level downward, with each inner list already in its zigzag direction.

Examples

Example 1

Input:  root = [3, 9, 20, null, null, 15, 7]

        3
       / \
      9   20
         /  \
        15   7

Output: [[3], [20, 9], [15, 7]]

Level 0 goes left-to-right ([3]), level 1 flips ([20, 9]), level 2 flips back ([15, 7]).

Example 2

Input:  root = [1, 2, 3, 4, 5, 6, 7]
Output: [[1], [3, 2], [4, 5, 6, 7]]

Odd-indexed levels are reversed; even-indexed levels keep natural order.

Example 3

Input:  root = []
Output: []

An empty tree produces an empty answer.

Constraints

  • The number of nodes is in the range [0, 2000].
  • -100 <= Node.val <= 100
  • Expected complexity: O(n) time — every node must be visited exactly once.

Think about it first

Hint 1 Do you already know how to produce a plain level-order traversal? Zigzag is that traversal plus one small twist.
Hint 2 Keep a flag (or use the level's index parity) telling you whether the current level should be reversed. You never need to change the order in which you *visit* nodes.
Hint 3 Standard BFS with a queue: pop one full level at a time into a list, then either append the list as-is or reversed depending on the level's parity. Alternatively, a deque lets you build each level in the correct order directly by choosing which end you write to.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug