Average of levels
Standard · Write code · about 10 min
Given the root of a binary tree, return the average value of the nodes on each level, from the root down. Answers within 0.00001 of the exact average are accepted.
Example 1
Input:
[[3,9,20,null,null,15,7]]
Output:
[3,14.5,11]
Level 1 holds 9 and 20, so its average is 29 / 2 = 14.5.
Example 2
Input:
[[1,2,3,4,5,null,6]]
Output:
[1,2.5,5]
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Level-order traversal, a visual lesson.
More Level-order traversal problems
- Who leaves the queue next? Warm-up
- Complete the level loop Warm-up
- Level order Standard
- Right side view Standard
- Zigzag level order Challenge