Average of Levels in Binary Tree - Problem

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array.

Answers within 10^-5 of the actual answer will be accepted.

Input & Output

Example 1 — Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [3.0,14.5,11.0]
💡 Note: Level 0: node 3 → average = 3.0. Level 1: nodes 9,20 → average = (9+20)/2 = 14.5. Level 2: nodes 15,7 → average = (15+7)/2 = 11.0
Example 2 — Single Node
$ Input: root = [1]
Output: [1.0]
💡 Note: Only one level with single node 1, so average is 1.0
Example 3 — Left-Heavy Tree
$ Input: root = [3,9,20,15,7]
Output: [3.0,14.5,11.0]
💡 Note: Level 0: node 3 → 3.0. Level 1: nodes 9,20 → 14.5. Level 2: nodes 15,7 → 11.0

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -231 ≤ Node.val ≤ 231 - 1

Visualization

Tap to expand
Average of Levels in Binary Tree INPUT Binary Tree Structure 3 9 20 15 7 L0 L1 L2 root = [3,9,20,null,null,15,7] Array representation ALGORITHM (BFS) 1 Initialize Queue Add root node to queue 2 Process Each Level Count nodes, sum values 3 Calculate Average avg = sum / count 4 Add Children Enqueue left/right children Level Processing Level Nodes Sum Avg 0 [3] 3 3.0 1 [9,20] 29 14.5 2 [15,7] 22 11.0 FINAL RESULT Averages per Level Level 0 3.0 Level 1 14.5 (9+20)/2 Level 2 11.0 (15+7)/2 Output Array: [3.0, 14.5, 11.0] OK - Complete! Key Insight: BFS naturally processes nodes level-by-level. Track the queue size at each level start to know how many nodes belong to current level. Sum their values, divide by count, and store the average. Time: O(n) | Space: O(w) where w is max width of tree TutorialsPoint - Average of Levels in Binary Tree | BFS Approach
Asked in
Amazon 35 Facebook 22 LinkedIn 18 Microsoft 15
185.0K Views
Medium Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen