AAlgoLoopSpaced repetition for LeetCode
EASYBFS / DFSLeetCode ↗

Average of Levels in Binary Tree

The key idea

Process the tree one level at a time. A breadth-first sweep naturally groups nodes by depth: before starting each round, the queue holds exactly that level's nodes, so you can sum them, divide by the count, then enqueue all their children for the next round.

Problem

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. The answer for each level is the sum of that level's node values divided by the number of nodes on the level. Answers within 10^-5 of the actual answer are accepted.

Constraints

Examples

Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000]
Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000]

Complexity

Time: O(n) Space: O(w)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems