637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

Question

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<sup>-5</sup> of the actual answer will be accepted.

Solution

BFS搜索,记录单层的总和sum和单层的个数count。
每次遍历一个层级的所有节点,并更新sum和count。
遍历完毕后将当层级的平均数加入列表,同时将sum和count清零。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();

double sum = 0, count = 0;
int level = 1;
q.add(root);

while(!q.isEmpty()){

for(int i = 0; i < level; i++){
TreeNode curr = q.poll();
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);
count++;
sum += curr.val;
}
res.add(sum/count);
sum = 0;
count = 0;
level = q.size();
}
return res;
}
}
Author

Xander

Posted on

2022-09-02

Updated on

2022-09-02

Licensed under

Comments