Implement zigzag level-order traversal
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of binary tree traversal, level-order processing with alternating directions, and the ability to reason about data structures and time/space complexity within the Coding & Algorithms domain.
Constraints
- The number of nodes is in the range [0, 2000].
- Node values fit in a 32-bit signed integer.
- The input array uses null placeholders for missing children and is a valid level-order encoding of a binary tree.
- An empty input array (or a leading null) represents an empty tree and returns an empty list.
Examples
Input: ([3, 9, 20, None, None, 15, 7],)
Expected Output: [[3], [20, 9], [15, 7]]
Explanation: Level 0 (L->R): [3]. Level 1 (R->L): nodes 9,20 read right-to-left -> [20, 9]. Level 2 (L->R): [15, 7].
Input: ([1],)
Expected Output: [[1]]
Explanation: A single node forms one level read left-to-right.
Input: ([],)
Expected Output: []
Explanation: An empty tree has no levels, so the result is an empty list.
Input: ([1, 2, 3, 4, 5, 6, 7],)
Expected Output: [[1], [3, 2], [4, 5, 6, 7]]
Explanation: A full tree of 7 nodes. Level 1 reverses 2,3 to 3,2; level 2 stays left-to-right.
Input: ([1, 2, None, 3, None, 4],)
Expected Output: [[1], [2], [3], [4]]
Explanation: A left-leaning chain (with nulls) — each level has a single node, so direction has no visible effect.
Input: ([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1],)
Expected Output: [[5], [8, 4], [11, 13, 4], [1, 2, 7]]
Explanation: Asymmetric tree with internal nulls. Level 1 reverses to [8, 4]; level 3 reverses [7, 2, 1] to [1, 2, 7].
Hints
- The 'level by level' requirement is the signature of breadth-first search (BFS): process the tree one level at a time using a queue.
- For each level, record how many nodes are currently in the queue before you start popping — that count is exactly the size of the current level, so you can isolate one level per outer iteration.
- You do not need two stacks or special pushing order. Build each level left-to-right as usual, then simply reverse the level's value list whenever it should be read right-to-left.
- Track a boolean that flips after every level to decide whether the just-collected level needs to be reversed.