Average of Levels in Binary Tree
LeetCode 637 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 actual answer will be accepted.
Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].
Example 2:

Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]
Constraints:
- The number of nodes in the tree is in the range `[1, 10^4]`.
- `-2^31 <= Node.val <= 2^31 - 1`
Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 328 ms)β
| Metric | Value |
|---|---|
| Runtime | 328 ms |
| Memory | N/A |
| Date | 2018-07-13 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<double> AverageOfLevels(TreeNode root) {
Queue<TreeNode> level = new Queue<TreeNode>();
List<double> result = new List<double>();
if (root == null) return result;
level.Enqueue(root);
while (level.Count != 0)
{
int rowCount = level.Count;
double sum = 0.0;
for (int i = 0; i < rowCount; i++)
{
var front = level.Dequeue();
if (front.left != null) level.Enqueue(front.left);
if (front.right != null) level.Enqueue(front.right);
sum += front.val;
}
result.Add(sum/(double)rowCount);
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.