1115. 二叉树每层的平均数
描述
给定非空二叉树,以数组的形式返回每一层上的节点的平均值。
样例 1:
输入:
3
/ \
9 20
/ \
15 7
输出:
[3, 14.5, 11]
解释:
第0层的节点的平均值是3,第一层的平均值是14.5, 第二层的平均值11,因此需要返回[3, 14.5, 11]
分析
按层序遍历,每次统计这一层的节点数和节点值之和。
题解
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the binary tree of the root
* @return: return a list of double
*/
public List<Double> averageOfLevels(TreeNode root) {
// write your code here
List<Double> ret = new ArrayList<>();
if (root == null) {
return ret;
}
// 第一层
ret.add(Double.valueOf(root.val));
// 将第二层入队
Queue<TreeNode> q = new LinkedList<>();
if (root.left != null) {
q.offer(root.left);
}
if (root.right != null) {
q.offer(root.right);
}
while (!q.isEmpty()) {
// 每次循环一层,记录节点数量,和节点值之和
int size = q.size();
double totalValue = 0;
for (int i = 0; i < size; ++i) {
TreeNode node = q.poll();
totalValue += node.val;
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
// 一层的平均值
ret.add(totalValue / size);
}
return ret;
}
}
最后说两句
非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~
作者水平有限,如果文章内容有不准确的地方,请指正。
希望小伙伴们都能每天进步一点点。
声明
本文由二当家的白帽子博客原创,转载请注明来源,谢谢~