-
Notifications
You must be signed in to change notification settings - Fork 0
/
637.二叉树的层平均值.java
53 lines (48 loc) · 1.2 KB
/
637.二叉树的层平均值.java
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
42
43
44
45
46
47
48
49
50
51
52
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.swing.tree.TreeNode;
/*
* @lc app=leetcode.cn id=637 lang=java
*
* [637] 二叉树的层平均值
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Double> result = new ArrayList<>();
TreeNode temp = null;
int size = 0;
double sum = 0;
int i = 0;
while(!queue.isEmpty()){
size = queue.size();
for(i = 0; i < size; i++){
temp = queue.poll();
sum+=temp.val;
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
result.add((double)(sum*1.0/i));
sum = 0;
}
return result;
}
}
// @lc code=end