【LeeCode】637.二叉树的层平均值

时间:2023-01-14 07:14:38

【题目描述】

给定一个非空二叉树的根节点 ​​root​​​ , 以数组的形式返回每一层节点的平均值。与实际答案相差 ​​10-5​ 以内的答案可以被接受。

​https://leetcode.cn/problems/average-of-levels-in-binary-tree/​

【示例】

【LeeCode】637.二叉树的层平均值

【代码】admin

思路: 求解出每层的元素然后利用stream求均值

package com.company;
// 2023-1-13
import java.util.*;
import java.util.stream.Collectors;

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) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Double>> res = new LinkedList<>();

if (root == null) return null;

queue.add(root);
while (!queue.isEmpty()){
int len = queue.size();
List<Double> list = new LinkedList<>();
while (len > 0){
TreeNode node = queue.poll();
list.add((double) node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
len--;
}
res.add(list);
}
System.out.println(res);
// 利用stream求均值
List<Double> collect = res.stream().map(x -> x.stream().mapToDouble(Double::doubleValue).average().getAsDouble()).collect(Collectors.toList());
return collect;
}
}
public class Test {
public static void main(String[] args) {

}
}

【代码】​​代码随想录​

package com.company;

import java.util.*;
import java.util.stream.Collectors;

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) {
Deque<TreeNode> queue = new LinkedList<>();
List<Double> list = new ArrayList<>();

if (root == null) return list;
queue.offerLast(root);

while (!queue.isEmpty()) {
int len = queue.size();
double sum = 0.0;
for (int i = 0; i < len; i++) {
TreeNode node = queue.pollFirst();
sum += node.val;
if (node.left != null) queue.offerLast(node.left);
if (node.right != null) queue.offerLast(node.right);
}
list.add(sum / len);
}
return list;
}
}
public class Test {
public static void main(String[] args) {

}
}