Average of Levels in Binary Tree - Problem
Calculate the Average Value at Each Level of a Binary Tree
You are given the
๐ฏ Goal: Traverse the binary tree level by level and calculate the mean value of nodes at each depth.
๐ฅ Input: The root node of a binary tree
๐ค Output: An array of floating-point numbers representing the average value at each level
Note: Answers within 10-5 of the actual answer will be accepted due to floating-point precision.
Example: For a tree with level 0: [3], level 1: [9, 20], level 2: [15, 7], the result would be [3.0, 14.5, 11.0]
You are given the
root of a binary tree. Your task is to compute the average value of all nodes at each level and return these averages as an array.๐ฏ Goal: Traverse the binary tree level by level and calculate the mean value of nodes at each depth.
๐ฅ Input: The root node of a binary tree
๐ค Output: An array of floating-point numbers representing the average value at each level
Note: Answers within 10-5 of the actual answer will be accepted due to floating-point precision.
Example: For a tree with level 0: [3], level 1: [9, 20], level 2: [15, 7], the result would be [3.0, 14.5, 11.0]
Input & Output
example_1.py โ Perfect Binary Tree
$
Input:
root = [3,9,20,null,null,15,7]
โบ
Output:
[3.00000,14.50000,11.00000]
๐ก Note:
Level 0: [3] โ average = 3.0, Level 1: [9,20] โ average = (9+20)/2 = 14.5, Level 2: [15,7] โ average = (15+7)/2 = 11.0
example_2.py โ Single Node Tree
$
Input:
root = [1]
โบ
Output:
[1.00000]
๐ก Note:
Only one level with a single node having value 1, so the average is 1.0
example_3.py โ Skewed Tree
$
Input:
root = [2,null,3,null,4,null,5,null,6]
โบ
Output:
[2.00000,3.00000,4.00000,5.00000,6.00000]
๐ก Note:
Each level has exactly one node, so each average equals the node's value: 2.0, 3.0, 4.0, 5.0, 6.0
Visualization
Tap to expand
Understanding the Visualization
1
Start at Ground Floor
Begin with root node (Floor 0) containing value 3
2
Process Floor 0
Record value 3, average = 3.0, note children are on Floor 1
3
Process Floor 1
Record values 9 and 20, average = (9+20)/2 = 14.5, note children are on Floor 2
4
Process Floor 2
Record values 15 and 7, average = (15+7)/2 = 11.0, no more floors
5
Final Result
Return array of averages: [3.0, 14.5, 11.0]
Key Takeaway
๐ฏ Key Insight: BFS naturally processes nodes level by level, making it perfect for calculating averages per level in a single traversal with optimal O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once during BFS traversal
โ Linear Growth
Space Complexity
O(w)
Queue stores at most w nodes where w is maximum width of tree (up to n/2 for complete binary tree)
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -231 โค Node.val โค 231 - 1
- Floating point precision: Answers within 10-5 of the actual answer will be accepted
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code