🧠 Approach: Level Order Traversal (BFS)
We use Breadth-First Search (BFS) to traverse the tree level by level.
Steps:
- Use a queue to traverse each level.
- For each level:
- Sum up all node values.
- Divide by the number of nodes in that level.
- Round the result to 5 decimal places.
- 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;
};
🧮 Example:
Input Tree:
3
/ \
9 20
/ \
15 7
Output:
[3.0, 14.5, 11.0]
⏱️ 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)