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
UnverifiedTime 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
Show helper code
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 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[] = [];
let level: TreeNode[] = [root];
while (level.length) {
const next: TreeNode[] = [];
let sum = 0;
for (const n of level) {
sum += n.val;
if (n.left) next.push(n.left);
if (n.right) next.push(n.right);
}
res.push(sum / level.length);
level = next;
}
return res;
}
export function averageOfLevels(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
let level: TreeNode[] = [root];
while (level.length) {
const next: TreeNode[] = [];
let sum = 0;
for (const n of level) {
sum += n.val;
if (n.left) next.push(n.left);
if (n.right) next.push(n.right);
}
res.push(sum / level.length);
level = next;
}
return res;
}
Template connection
Level snapshot. The recorded value is the sum of the nodes popped in that round, divided by the round’s size.
Reflection
- The average is the level sum divided by the level size. Integer division cuts the fraction. Python
/keeps it; C# integer/does not. - Negatives pull the sum down. One node is itself. An empty tree is empty.
- A large sum can overflow
int. Keep the accumulator wide.