Skip to content
DSA Patterns
Menu
Language
Tree BFSLC #6375 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time 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.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Average of each level on 3 / 9, 20 / 15, 7. Level BFS; the payload is sum / count.

3q920157

avg = []

Key:CurrentActive rangeMatchSettled