AlgoInsight

DSA problem

Average of Levels in Binary Tree

EasyTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop600AmazonMicrosoftFacebookGoogleApple

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10^-5 of the true value are accepted.

This is a textbook level-order problem. Each level of the tree is processed as a self-contained batch: we sum the node values on the level, divide by the count, and append the result to the output array. The tree's structure is incidental — only the grouping of nodes by depth matters.

The key implementation subtlety is numeric overflow. Node values can be as large as 2^31 - 1 in magnitude, and a level may contain up to about 10^4 nodes. The sum can therefore exceed the 32-bit signed integer range, so in Java the running sum must be a long (or you can use double directly), and in C++ a long long. In Python and JavaScript the native number types handle this automatically.

We implement a standard BFS: enqueue the root, then for each outer iteration snapshot the queue size, dequeue exactly that many nodes, accumulate their values into a wide-enough sum, enqueue their children, and finally push sum / size (as a floating-point number) to the result. The algorithm visits each node once, giving O(n) time and O(w) space.

Examples

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [3.0, 14.5, 11.0]
Explanation: Level 0 has one node (3) → avg 3.0. Level 1 has [9, 20] → avg 14.5. Level 2 has [15, 7] → avg 11.0.
Example 2
Input: root = [3,9,20,15,7]
Output: [3.0, 14.5, 11.0]
Explanation: A complete tree of three levels: averages are 3, (9+20)/2 = 14.5, and (15+7)/2 = 11.
Example 3
Input: root = [1]
Output: [1.0]
Explanation: A single-node tree has only one level whose average equals the root value.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderqueue

Browse all DSA problems