Average of Levels in Binary Tree
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array.
The average of a level is calculated as:
average=number of nodes/sum of node values
Return the averages from the top level to the bottom level.
Example 1
Input
n = 7 root = [3,9,20,-1,-1,15,7]
Output
3 14.5 11
Explanation
The tree has three levels:
- Level 1: [3] → average = 3
- Level 2: [9,20] → average = 14.5
- Level 3: [15,7] → average = 11
Therefore, the answer is:
3 14.5 11
Example 2
Input
n = 7 root = [3,9,20,15,7,-1,-1]
Output
3 14.5 11
Explanation
The levels are:
[3]
[9,20]
[15,7]
Their averages are 3, 14.5, and 11.
Constraints
Hints:
Hint 1
Use Breadth-First Search (BFS) to process the tree one level at a time.
Hint 2
For each level, calculate the sum of all node values and divide it by the number of nodes in that level.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 20, 2026
Last updated
Aug 20, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output