Skip to problem
←

Binary Tree Level Order Traversal

Medium 0 attempts
Daily

You're given the root of a binary tree. Return its values grouped level by level, from the root downward, reading each level from left to right.

Function contract

Implement levelOrder(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: An array of levels, each containing values from left to right. Return [] for an empty tree.

Example 1

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

Example 2

Input
root = []
Output
[]
Visual Aid
Group nodes by depth
3920157Levels: [3], [9, 20], [15, 7]

Keep the left-to-right order within each level; do not include missing children.

Constraints
  • 0 <= number of nodes <= 2000
  • -1000 <= Node.val <= 1000

BFS with Queue

Process nodes level by level using a queue.

javascript
function levelOrder(root) {
  if (!root) return [];
  const result = [], q = [root];
  let head = 0;
  while (head < q.length) {
    const level = [], size = q.length - head;
    for (let i = 0; i < size; i++) {
      const node = q[head++];
      level.push(node.val);
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
    result.push(level);
  }
  return result;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript