λ¬Έμ νμ
κ° level(depth)
μ λ
Έλλ€μ val
κ° νκ· μ ꡬν΄μ λ°νν΄μΌνλ€.
νμ΄
1οΈβ£ κ·Έλν νμμ μ΄μ©ν νμ΄ (μ μ νμ)
π‘ λ μ€λ₯Έ Idea
μ μ νμμdepth
λ₯Ό 1μ© μ¦κ°μν€λ©΄μ νμμ νλ€.
κ°depth
μ λλ¬νμ λ, ν΄λΉdepth
μ ν©κ³Ό κ°μλ₯Ό μ μ₯νλList
λ₯Ό ν΅ν΄ μ 보λ₯Ό κ°±μ νλ€.
νμμ΄ λλκ³ λμ, νκ· κ°μ ꡬν΄μ λ°νν΄μ€λ€.
import java.util.*;
class Solution {
List<Info> list = new ArrayList<>();
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans = new ArrayList<>();
preOrder(root, 0);
for (int i = 0; i < list.size(); i++) {
Info info = list.get(i);
ans.add(info.sum / info.cnt);
}
return ans;
}
private void preOrder(TreeNode node, int depth) {
if (node == null) {
return;
}
if (list.size() <= depth) {
list.add(new Info(1, (double) node.val));
} else {
Info info = list.get(depth);
info.cnt++;
info.sum += node.val;
}
preOrder(node.right, depth + 1);
preOrder(node.left, depth + 1);
}
static class Info{
int cnt;
double sum;
public Info(int cnt, double sum) {
this.cnt = cnt;
this.sum = sum;
}
}
}
κ²°κ³Ό
2οΈβ£ bfsλ₯Ό μ΄μ©ν λ°©λ²
π‘ λ μ€λ₯Έ Ideadepth
λ³λ‘ ν©μ ꡬνκ³ μΉ΄μ΄ν μ ν λ€,depth
κ° λ¬λΌμ§λ μμ μ νκ· κ°μ ꡬνλ λ°©μλ μ¬μ©ν μ μκ² λ€ μΆμλ€.
λ°λΌμ, λμ΄ μ°μ νμ λ°©μμΈbfs
λ°©μμΌλ‘ ꡬνν΄λ³΄μλ€.
class Solution {
Queue<Info> q = new LinkedList<>();
List<Double> ans = new ArrayList<>();
public List<Double> averageOfLevels(TreeNode root) {
if (root != null) {
q.offer(new Info(root, 0));
}
int prevDepth = 0;
double sum = 0;
int cnt = 0;
while (!q.isEmpty()) {
Info info = q.poll();
TreeNode node = info.node;
int depth = info.depth;
if (depth == prevDepth) {
sum += node.val;
cnt++;
} else {
ans.add(sum / cnt);
prevDepth = depth;
sum = node.val;
cnt = 1;
}
if (node.left != null) {
q.offer(new Info(node.left, depth + 1));
}
if (node.right != null) {
q.offer(new Info(node.right, depth + 1));
}
}
ans.add(sum / cnt);
return ans;
}
static class Info {
TreeNode node;
int depth;
public Info(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
}
κ²°κ³Ό
νΈλ¦¬λ₯Ό νμνλ λ°©μ보λ€λ μκ°μ΄ μ‘°κΈλ μμλμλ€.
π νκ³
νΈλ¦¬λ₯Ό μννλ λ°©μμΌλ‘λ ꡬνν΄λ³΄κ³ νλ₯Ό μ΄μ©ν bfs λ°©μμΌλ‘λ λ¬Έμ λ₯Ό ν΄κ²°ν΄λ³΄μλ€.
μ¬λ¬κ°μ§ μ κ·ΌμΌλ‘ νμ΄λ³΄λ νΈλ¦¬μ ꡬ쑰μ λν΄ λ μμΈνκ² μκ² λ κ² κ°λ€.