链接
637. Average of Levels in Binary Tree
题意
给定非空二叉树,求出每一层数的平均值
思路
利用队列存储每一层的数,存完之后需要取出size,再循环求平均值。这样保证了循环的次数就是每一层的结点数。
代码
/**
* 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) {
List<Double> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
if (root == null) return result;
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
double sum = 0.0;
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
sum += node.val;
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
result.add(sum / size);
}
return result;
}
}