https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
题目描述:
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
思路:
类比二叉树的层序遍历,建立一个辅助的队列,在队列中进行遍历,如果此结点有左儿子,将其入队,如果有右儿子,将其入队,接着沿队列向下遍历。
这道题目中要求计算每一层的平均值,故如何知道队列中的哪些结点是这一层的呢?初到一层的结点的时候,统计一下队列中元素的个数就可以了,因为Queue<>接口实现了Collection<>接口,LinkedList<>类作为Queue<>和Collection<>的实现类,具有Collection<>接口中的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> list = new ArrayList<Double>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
int len;
q.add(root);
double sum;
TreeNode current;
while(!q.isEmpty()){
len = q.size();
sum = 0.0;
for(int i = 0; i<len;i ++){
current = q.remove();
sum += current.val;
if(current.left!=null) q.add(current.left);
if(current.right!=null) q.add (current.right);
}
list.add(sum/len);
}
return list;
}
}