题解 | #牛群平均重量#
牛群平均重量
https://www.nowcoder.com/practice/9b826d0a84034e8e8afd4c451f7d34e0
知识点
树,层序遍历
解题思路
层序遍历树(使用两个双端队列),记录每一层的数量和累加值,将每一层的结果记录到list集合中,最后将结果通过stream转换为数组输出。
Java题解
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return double浮点型一维数组 */ public double[] averageOfLevels (TreeNode root) { // write code here Deque<TreeNode> outer = new LinkedList<>(); Deque<TreeNode> inner = new LinkedList<>(); if(root != null) outer.offerFirst(root); List<Double> list = new ArrayList<>(); while (!outer.isEmpty()){ while(!outer.isEmpty()){ inner.offerFirst(outer.pollLast()); } double sum = 0; int n = inner.size(); while(!inner.isEmpty()){ TreeNode treeNode = inner.pollLast(); sum += treeNode.val; if(treeNode.left != null) outer.offerFirst(treeNode.left); if(treeNode.right != null) outer.offerFirst(treeNode.right); } list.add(sum / n); } return list.stream().mapToDouble(Double::doubleValue).toArray(); } }