Coding problem · Medium · Trees

Binary Tree Level Order Traversal

Medium Algorithms & data structures Most askedSeen at Amazon, Meta, Microsoft, LinkedIn

Given the root of a binary tree, return the level order traversal of its values: a list of levels, each listing values from left to right.

Example 1

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

Hints

Hint 1

Use a queue. Process exactly the nodes currently in the queue to build one level.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(w) where w is the widest level

Breadth-first search with a queue: at the start of each round, the queue holds exactly one level. Pop that many nodes, record their values, and enqueue their children.

Reference solution

function levelOrder(root) {
  const out = [];
  let level = root ? [root] : [];
  while (level.length) {
    out.push(level.map((n) => n.val));
    level = level.flatMap((n) => [n.left, n.right].filter(Boolean));
  }
  return out;
}

Follow-up questions

  • Zigzag order
  • Right side view (last value of each level)