Binary Tree Zigzag Level Order Traversal

MediumTreeslevel order

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, return its node values level by level, alternating direction. The root level (depth 0) is read **left to right**, the next level **right to left**, the one after that left to right again, and so on. Return a list of lists where the i-th inner list holds the values at depth i in that level's reading direction. An empty tree returns []. A breadth-first traversal that reverses every other level runs in O(n) time.

Examples

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Depth 1 is read right to left, giving 20 then 9.
Input: root = [1]
Output: [[1]]
Only the root level.
Input: root = []
Output: []
An empty tree has no levels.

Constraints

  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100
  • Values may repeat

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More level order problems