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.
Input: root =[3,9,20,null,null,15,7]Output: [3.00000,14.50000,11.00000]Explanation: The average value of nodes on level 0is3, on level 1is14.5, and on level 2is11.Hence return[3,14.5,11].
The key idea is to process the tree level by level using a queue (Breadth-First Search). For each level, sum the node values and divide by the number of nodes at that level to get the average.
classSolution {
public List<Double>averageOfLevels(TreeNode root) {
List<Double> ans =new ArrayList<>();
Queue<TreeNode> q =new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int n = q.size();
double sum = 0;
for (int i = 0; i < n; i++) {
TreeNode node = q.poll();
sum += node.val;
if (node.left!=null) q.offer(node.left);
if (node.right!=null) q.offer(node.right);
}
ans.add(sum / n);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funaverageOfLevels(root: TreeNode?): List<Double> {
val ans = mutableListOf<Double>()
val q = ArrayDeque<TreeNode>()
if (root !=null) q.add(root)
while (q.isNotEmpty()) {
val n = q.size
var sum = 0.0 repeat(n) {
val node = q.removeFirst()
sum += node.`val`
node.left?.let { q.add(it) }
node.right?.let { q.add(it) }
}
ans.add(sum / n)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defaverageOfLevels(self, root: Optional[TreeNode]) -> list[float]:
ans: list[float] = []
q: list[TreeNode] = [root]
while q:
n = len(q)
s =0for _ in range(n):
node = q.pop(0)
s += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(s / n)
return ans