🧠 Approach: Breadth-First Search (BFS)
This is a textbook case for BFS using a queue. You process nodes level by level, tracking all nodes at each depth before moving to the next.
Steps:
- Use a queue initialized with the root node.
- At each level:
- Record all node values into an array.
- Add their children to the queue.
- Push the level array into the final result.
 
✅ Code (JavaScript):
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val === undefined ? 0 : val);
 *     this.left = (left === undefined ? null : left);
 *     this.right = (right === undefined ? null : right);
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
  if (root === null) return [];
  const result = [];
  const queue = [root];
  while (queue.length > 0) {
    const levelSize = queue.length;
    const level = [];
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      level.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
    result.push(level);
  }
  return result;
};
🧮 Example:
Input Tree:
       3
      / \
     9  20
        / \
       15  7
Output:
[
  [3],
  [9, 20],
  [15, 7]
]
⏱️ Time & Space Complexity
| Type | Complexity | 
|---|---|
| Time | O(n) — Visit every node once | 
| Space | O(n) — Queue and result array can hold all nodes | 
 

 
    
Top comments (0)