DSA · Trees · #36
Average of Levels in Binary Tree
Module 44 · difficulty 2/5·⏱ 30:00starts on first keystroke
Given the `root` of a binary tree, return the average value of the nodes on each level, from top to bottom, as an array of floating-point numbers. Implement `averageOfLevels(root)`. Each tree node has shape `{ val, left, right }` where `left` and `right` are child nodes or `null`. The returned array's i-th element is the mean of all node values at depth `i` (root is depth 0). Answers within 1e-5 of the actual value are accepted.
Examples
root = [3,9,20,null,null,15,7]→[3.0, 14.5, 11.0]— Level 0: 3 -> 3. Level 1: (9+20)/2 = 14.5. Level 2: (15+7)/2 = 11.root = [3,9,20,15,7]→[3.0, 14.5, 11.0]— Level 1: (9+20)/2 = 14.5. Level 2: (15+7)/2 = 11.root = [1]→[1.0]— A single node yields one level average.
Constraints
- · The number of nodes is in the range [1, 10^4].
- · -2^31 <= Node.val <= 2^31 - 1
- · Use running sums (not products) so large levels do not overflow.
- · Return values are floating-point; integer levels still return e.g. 3 (=== 3.0 in JS).
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.