java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846 |
---|
- 使用广度优先遍历,按层遍历即可,遍历过程中,记录每层的结点和,最后将其平均数求出
- 使用深度优先遍历,需要记录当前结点的层次,然后必须使用一个可以通过下标获取值的容器来记录每个结点值
深度遍历时,将当前结点值累加到当前结点所在层次对应的地方,也就是容器对应下标(下标代表层次)位置。
1. 广度优先
代码:给出两种代码思路,一种是普通做法,第二种是直接在生成容器时,静态构建,因此第二种非常快,作为扩展了解即可 |
---|
- 普通方法
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<>();
Queue<TreeNode> bfs_queue = new LinkedList<>();
bfs_queue.offer(root);
while(!bfs_queue.isEmpty()){
int size = bfs_queue.size();
long sum = 0;
for(int i = 0;i<size;i++){
TreeNode poll = bfs_queue.poll();
sum+=poll.val;
if(poll.left!=null) bfs_queue.offer(poll.left);
if(poll.right!=null)bfs_queue.offer(poll.right);
}
list.add((double)sum/size);
}
return list;
}
}
- 进阶方法
import java.util.AbstractList;
class Solution {
public static List<Double> averageOfLevels(TreeNode root) {
return new AbstractList<Double>() {
private final List<Double> list = new ArrayList<>();
private final List<TreeNode> level = new ArrayList<>();
@Override
public Double get(int index) {
init();
return list.get(index);
}
@Override
public int size() {
init();
return list.size();
}
void init() {
if (list.isEmpty()) {
level.add(root);
while (!level.isEmpty()) {
levelTraverse(level);
}
}
}
void levelTraverse(List<TreeNode> level) {
int count = level.size();
long sum = 0;
for (int i = 0; i < count; i++) {
TreeNode tree = level.get(0);
sum += tree.val;
if (tree.left != null) {
level.add(tree.left);
}
if (tree.right != null) {
level.add(tree.right);
}
level.remove(0);
}
list.add((double) sum / count);
}
};
}
}
2. 深度优先
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Integer> counts = new ArrayList<Integer>();
List<Double> sums = new ArrayList<Double>();
dfs(root, 0, counts, sums);
List<Double> averages = new ArrayList<Double>();
int size = sums.size();
for (int i = 0; i < size; i++) {
averages.add(sums.get(i) / counts.get(i));
}
return averages;
}
public void dfs(TreeNode root, int level, List<Integer> counts, List<Double> sums) {
if (root == null) return;
if (level < sums.size()) {
sums.set(level, sums.get(level) + root.val);
counts.set(level, counts.get(level) + 1);
} else {
sums.add(1.0 * root.val);
counts.add(1);
}
dfs(root.left, level + 1, counts, sums);
dfs(root.right, level + 1, counts, sums);
}
}