Skip to content

Commit 8ab323e

Browse files
authored
[20251208] BOJ / G5 / 트리 / 이종환
1 parent d7b6f82 commit 8ab323e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

0224LJH/202512/08 BOJ 트리.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
```java
2+
3+
import java.util.StringTokenizer;
4+
import java.util.*;
5+
import java.io.*;
6+
7+
public class Main {
8+
9+
static int nodeCnt,ans;
10+
static Node[] nodes;
11+
static Node root;
12+
13+
static class Node {
14+
Node parent;
15+
boolean alive = true;
16+
Set<Node> children = new HashSet<>();
17+
18+
public void checkLeaf() {
19+
int childCnt = 0;
20+
for (Node n: children) {
21+
if (!n.alive) continue;
22+
childCnt++;
23+
n.checkLeaf();
24+
}
25+
if (childCnt==0) ans++;
26+
}
27+
28+
}
29+
30+
31+
public static void main(String[] args) throws IOException {
32+
init();
33+
process();
34+
print();
35+
36+
}
37+
38+
private static void init() throws IOException{
39+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
40+
nodeCnt = Integer.parseInt(br.readLine());
41+
ans = 0;
42+
43+
nodes = new Node[nodeCnt];
44+
for (int i = 0; i < nodeCnt; i++) {
45+
nodes[i] = new Node();
46+
}
47+
StringTokenizer st = new StringTokenizer(br.readLine());
48+
for (int i = 0; i < nodeCnt; i++) {
49+
int parent = Integer.parseInt(st.nextToken());
50+
if (parent == -1) {
51+
root = nodes[i];
52+
continue;
53+
}
54+
Node p = nodes[parent];
55+
nodes[i].parent = p;
56+
p.children.add(nodes[i]);
57+
}
58+
59+
int targetNum = Integer.parseInt(br.readLine());
60+
Node target = nodes[targetNum];
61+
target.alive = false;
62+
63+
}
64+
65+
private static void process() throws IOException {
66+
if (root.alive) root.checkLeaf();
67+
68+
}
69+
70+
private static void print() {
71+
System.out.println(ans);
72+
}
73+
74+
}
75+
```

0 commit comments

Comments
 (0)