Skip to main content

11. Binary Tree Level Order Traversal

mediumAsked at Byju's

Return the node values of a binary tree grouped by level.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, return the level order traversal of its nodes' values, grouped per level from left to right. An empty tree should return an empty array. Each level's nodes appear in a sub-array.

Constraints

  • 0 <= nodes <= 2000
  • -1000 <= Node.val <= 1000

Examples

Example 1

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

Example 2

Input
root = [1]
Output
[[1]]

Approaches

1. DFS with depth tag

Recurse with a depth parameter and append into result[depth].

Time
O(n)
Space
O(n)
const res=[];
const dfs=(n,d)=>{ if(!n) return; if(!res[d]) res[d]=[]; res[d].push(n.val); dfs(n.left,d+1); dfs(n.right,d+1); };
dfs(root,0);
return res;

Tradeoff:

2. Iterative BFS

Process the queue one level at a time using its current length as the level size. Each iteration emits one row.

Time
O(n)
Space
O(n)
function levelOrder(root) {
  if (!root) return [];
  const res = [], q = [root];
  while (q.length) {
    const level = [], size = q.length;
    for (let i = 0; i < size; i++) {
      const n = q.shift();
      level.push(n.val);
      if (n.left) q.push(n.left);
      if (n.right) q.push(n.right);
    }
    res.push(level);
  }
  return res;
}

Tradeoff:

Byju's-specific tips

Byju's adaptive-learning teams ask level-order traversal because it mirrors how their grade-by-grade curriculum tree expands outward from a topic root.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Binary Tree Level Order Traversal and other Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →