← Questions

Binary tree zigzag level-order traversal

0
GoogleMicrosoftCodingLast asked Apr 2026

A coding interview question asked in Microsoft's coding round and at Google, last asked Apr 2026. It tests trees and bfs.

Given a binary tree, return its node values level by level, alternating direction: the first level left to right, the second right to left, the third left to right, and so on.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class TreeNode: val: int; left, right: TreeNode | None
  • zigzag(root: TreeNode | None) -> list[list[int]] — one list per level; [] for an empty tree.

Example

        3
       / \
      9   20
         /  \
        15   7

zigzag(root)  ->  [[3], [20, 9], [15, 7]]

        1
       / \
      2   3
     / \ / \
    4  5 6  7

zigzag(root)  ->  [[1], [3, 2], [4, 5, 6, 7]]

A single node gives [[1]].

Constraints

  • Up to 2000 nodes; values in [-10^4, 10^4].

Clarifying questions

  • Does the first level go left to right?
  • Should empty levels be skipped (they can't occur in a tree)?
  • What should an empty tree return?
  • Is the tree given as nodes or as a level-order array with None gaps?

What a strong answer covers

  • BFS by levels: process exactly the current queue length each round, collect the level left to right, and reverse it on odd levels. O(n) time, O(width) space.
  • An alternative that avoids the reverse: fill each level's list from the end, or use a deque and append on alternating sides.
  • The two-stack approach and why it works.
  • Tests: empty tree, single node, a skewed tree, a full tree.

Follow-ups

  • Return the right side view of the tree (the last node of each level).
  • Return each level's average.
  • Do it with DFS, carrying the depth.

Where it's asked

  • Microsoft · Coding · Last asked Apr 202660 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
  • Google · First round: coding · Last asked Aug 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

trees · bfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding