Average of Levels in Binary Tree
Average of Levels in Binary Tree
Return the average value of the nodes on each level in a binary tree.
Function signature
func AverageOfLevels(root *TreeNode) []float64
Inputs / outputs
root: root of the tree.- Return: slice where each entry is the average of one level.
Example
3
/ \
9 20
/ \
15 7
Output: [3.0, 14.5, 11.0]
Constraints
- 0 <= number of nodes <= 100_000
- node values fit in 32-bit signed int
Core idea (near-solution)
Use BFS to traverse level by level. For each level, sum values using 64-bit integers, then divide by the count to produce a float.
Invariant: the queue holds exactly the nodes for the current level when you start processing it.
Algorithm (step-by-step)
- If root is nil, return empty.
- Push root into queue.
- While queue not empty:
- Let
nbe queue size. - Pop
nnodes, add their values tosum, enqueue children. - Append
float64(sum)/float64(n)to result.
- Let
Correctness sketch
- Invariant: the queue holds exactly the nodes for the current level when you start processing it.
- The queue holds exactly the current level’s nodes before each level pass.
- Processing
sizenodes and enqueueing children builds the next level correctly. - Collected level results therefore match the required traversal.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
3
/ \
9 20
/ \
15 7
Output: [3.0, 14.5, 11.0]
Walk:
- level 0 sum=3 count=1 -> avg 3.0
- level 1 sum=9+20=29 count=2 -> avg 14.5
- level 2 sum=15+7=22 count=2 -> avg 11.0
Pitfalls to avoid
- Forgetting to reset the sum and count for each level.
- Using
intfor sums when node values can overflow; useint64.
Complexity
- Time:
O(n) - Extra space:
O(n).
Implementation notes (Go)
- Use
int64for sums, then convert tofloat64. - Reset sum/count each level; capture level size up front.
Run tests to see results
No issues detected