Easytree-bfs
Average of Levels in Binary Tree
Problem (restated)
Return the average value of the nodes on each level as an array of doubles.
Intuition
Level BFS; sum/count for each level.
Approaches
Level BFS average
Tested onlyTime O(n)Space O(w)
Idea. For each level size, accumulate sum, push sum/size.
Walkthrough. [3,9,20,null,null,15,7] → [3, 14.5, 11].
Trade-offs. Same skeleton as level order; only aggregate differs.
Solution
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val; this.left = left; this.right = right;
}
}
export function averageOfLevels(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
let sum = 0;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
sum += n.val;
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
res.push(sum / size);
}
return res;
}
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val; this.left = left; this.right = right;
}
}
export function averageOfLevels(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
let sum = 0;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
sum += n.val;
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
res.push(sum / size);
}
return res;
}
Template connection
Tree BFS per-level aggregate.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?