?思路:在层序遍历的时候把每层求个总和在求平均
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
//返回的结果
List<Double> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
//根节点入队
queue.add(root);
while(!queue.isEmpty()){
int levelCount = queue.size();
double n=0.0;
//添加节点到一层的List中去
for(int i = 0; i < levelCount ; i ++){
//节点出队
TreeNode node = queue.remove();
n=n+node.val;
//节点的左子树入队
if(node.left != null){
queue.add(node.left);
}
//节点的右子树入队
if(node.right != null){
queue.add(node.right);
}
}
res.add(n/levelCount);
}
return res;
}
}
|