637. Average of Levels in Binary Tree
Given the root
of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within of the actual answer will be accepted.
root
노드알고리즘 기본 전략 : 회귀를 사용
알고리즘 전략
Average
객체를 정의한다.List<Average>
객체와 오른쪽 노드의 각 계층별 정보를 담은 List<Average>
객체를 가져온다.class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Average> averages = averageOfLevelsByAverage(root);
List<Double> answer = new ArrayList<>();
for (int i = 0; i < averages.size(); i++) {
answer.add(averages.get(i).getAverage());
}
return answer;
}
private List<Average> averageOfLevelsByAverage(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}
List<Average> left = averageOfLevelsByAverage(root.left);
List<Average> right = averageOfLevelsByAverage(root.right);
List<Average> longList = left.size() >= right.size() ? left : right;
List<Average> shortList = left.size() >= right.size() ? right : left;
for (int i = 0; i < shortList.size(); i++) {
longList.get(i).concat(shortList.get(i));
}
longList.add(0, new Average(root.val));
return longList;
}
// Average 객체 정의
class Average {
private long count = 1;
private long sum;
public Average(int element) {
sum = element;
}
public void concat(Average average) {
if (average == null) {
return;
}
this.count += average.count;
this.sum += average.sum;
}
public double getAverage() {
return (double) sum / count;
}
}
}
알고리즘 전략
Queue
를 생성하고 root
를 넣음Queue
가 비어있을 때까지 반복Queue
에 있는 노드들의 평균 값을 구함Queue
에 넣는다.위 답안보다 더 좋은 점
배운 점
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> averages = new ArrayList<>();
if (root == null) {
return averages;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
double sum = 0l;
for (int i = 0; i < count; i++) {
TreeNode curr = queue.poll();
sum = sum + (double) curr.val;
if (curr.left != null) {queue.add(curr.left);}
if (curr.right != null) {queue.add(curr.right);}
}
averages.add(sum / count);
}
return averages;
}
}