Average of Levels in Binary Tree
给一个二叉树, 返回每层的均值. 直接层遍历即可.
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
List<Double> res = new ArrayList<>();
while(!q.isEmpty()) {
int size = q.size();
double sum = 0;
for(int i = 0; i < size; i++) {
TreeNode node = q.remove();
sum += node.val;
if(node.left != null)
q.add(node.left);
if(node.right != null)
q.add(node.right);
}
res.add(sum / size);
}
return res;
}
}