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: Input → Process → Output3920157Input TreeLevel ProcessingL0: [3]L1: [9,20]L2: [15,7]Sum ÷ CountOutput Array3 ÷ 1 = 3.029 ÷ 2 = 14.522 ÷ 2 = 11.0[3.0, 14.5, 11.0]
Understanding the Visualization
1
Input Tree
Binary tree with nodes arranged in levels
2
Level Grouping
Group nodes by their depth level
3
Average Calculation
Compute average for each level
Key Takeaway
🎯 Key Insight: Use BFS to process complete levels at once for efficient average calculation
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