Skip to content

Commit f302129

Browse files
authored
Merge pull request #1228 from AlgorithmWithGod/Seol-JY
[20251025] BOJ / G5 / 트리 / 설진영
2 parents 5e79b43 + 286330a commit f302129

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N;
7+
static List<Integer>[] tree;
8+
static boolean[] removed;
9+
static int deleteNode;
10+
11+
public static void main(String[] args) throws IOException {
12+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
14+
N = Integer.parseInt(br.readLine());
15+
tree = new ArrayList[N];
16+
removed = new boolean[N];
17+
18+
for (int i = 0; i < N; i++) {
19+
tree[i] = new ArrayList<>();
20+
}
21+
22+
StringTokenizer st = new StringTokenizer(br.readLine());
23+
int root = -1;
24+
25+
for (int i = 0; i < N; i++) {
26+
int parent = Integer.parseInt(st.nextToken());
27+
if (parent == -1) {
28+
root = i;
29+
} else {
30+
tree[parent].add(i);
31+
}
32+
}
33+
34+
deleteNode = Integer.parseInt(br.readLine());
35+
36+
removeNode(deleteNode);
37+
38+
if (removed[root]) {
39+
System.out.println(0);
40+
return;
41+
}
42+
43+
System.out.println(countLeaf(root));
44+
}
45+
46+
static void removeNode(int node) {
47+
removed[node] = true;
48+
for (int child : tree[node]) {
49+
removeNode(child);
50+
}
51+
}
52+
53+
static int countLeaf(int node) {
54+
if (removed[node]) return 0;
55+
56+
int childCount = 0;
57+
int leafCount = 0;
58+
59+
for (int child : tree[node]) {
60+
if (!removed[child]) {
61+
childCount++;
62+
leafCount += countLeaf(child);
63+
}
64+
}
65+
66+
return childCount == 0 ? 1 : leafCount;
67+
}
68+
}
69+
```

0 commit comments

Comments
 (0)