/*
* @lc app=leetcode.cn id=637 lang=java
*
* [637] 二叉树的层平均值
*
* https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/
*
* algorithms
* Easy (56.65%)
* Total Accepted: 3.9K
* Total Submissions: 6.9K
* Testcase Example: '[3,9,20,15,7]'
*
* 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
*
* 示例 1:
*
* 输入:
* 3
* / \
* 9 20
* / \
* 15 7
* 输出: [3, 14.5, 11]
* 解释:
* 第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
*
*
* 注意:
*
*
* 节点值的范围在32位有符号整数范围内。
*
*
*/
/**
* 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> resultList = new ArrayList<Double>();
if (root == null) {
return null;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(root);
while (!list.isEmpty()) {
double sum = 0.0;
int size = list.size();
for (int i=0;i<size;i++) {
TreeNode currentNode = list.poll();
sum+=currentNode.val;
if (currentNode.left != null) {
list.add(currentNode.left);
}
if (currentNode.right != null) {
list.add(currentNode.right);
}
}
resultList.add(sum/size);
}
return resultList;
}
}