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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code