Problem 637 · LeetCode 637(opens in a new tab)
Average of Levels in Binary Tree
EasyBreadth-first search
You are given the root of a binary tree. Group its nodes by level: the root alone is level 0, its children are level 1, their children are level 2, and so on.
Return a list with the average of the node values on each level, from the top level down. An answer within 0.00001 of the true value counts as correct.
Example 1
Input: root = [4, 3, 8, null, 5, 6, 10] Output: [4.0, 5.5, 7.0] Why: levels are [4], [3, 8] and [5, 6, 10]
1 more example and the constraints
Example 2
Input: root = [-5, 10, -2] Output: [-5.0, 4.0] Why: (10 + (-2)) / 2 = 4
Constraints
- The tree has between 1 and 10,000 nodes
- Each node value is a 32-bit signed integer, from −2,147,483,648 to 2,147,483,647
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS with a total per depthO(n)
- BFS, one level at a timeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| DFS with a total per depth | O(n) | Passes; deep trees need a big stack | |
| BFS, one level at a time | O(n) | Best; levels come for free |
n = number of nodes, h = tree height, w = widest level. Both touch every node once.
Edge cases to test
- One node. [0] gives [0.0].
- Huge values. Three nodes of 2,147,483,647 overflow a 32-bit sum; use a 64-bit total.
- A chain. [1, 2, null, 3] has one node per level, so each average is the node itself.
- Averages that do not end. A level of 1, 0, 0 averages to 0.333…; return it as a decimal, not 0.
Common mistakes
- Dividing two integers, so 11 / 2 becomes 5 instead of 5.5.
- Adding values in a 32-bit int, which overflows on large values.
- Reading the queue size inside the loop instead of once per level, so the next level leaks in.
How to talk through it
- 1Clarify. Can the tree be empty? How big can values get, and how precise must the answer be?
- 2Name the traversal. One answer per level means level-order traversal, so BFS.
- 3Explain the size trick. At the start of each round, the queue holds exactly one level; record its size before popping.
- 4Code it. Use a 64-bit total and floating-point division, and say why.
- 5Test out loud. Run a single node, a chain and a level of huge values.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?