DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 637. Average of Levels in Binary Tree

🧠 Approach: Level Order Traversal (BFS)

We use Breadth-First Search (BFS) to traverse the tree level by level.

Steps:

  1. Use a queue to traverse each level.
  2. For each level:
  • Sum up all node values.
  • Divide by the number of nodes in that level.
  • Round the result to 5 decimal places.
    1. Push the average to the result array.

✅ 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[]}
 */

const roundToDecimals = (num, places) => parseFloat(num.toFixed(places));

var averageOfLevels = function (root) {
  const result = [];
  const queue = [root];

  while (queue.length > 0) {
    const levelSize = queue.length;
    let sum = 0;

    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      sum += node.val;

      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }

    const average = roundToDecimals(sum / levelSize, 5);
    result.push(average);
  }

  return result;
};
Enter fullscreen mode Exit fullscreen mode

🧮 Example:

Input Tree:

       3
      / \
     9  20
        / \
       15  7
Enter fullscreen mode Exit fullscreen mode

Output:

[3.0, 14.5, 11.0]
Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity

Type Complexity
Time O(n) — Each node is visited once
Space O(n) — Queue stores nodes level by level

Top comments (0)