Skip to content

Commit 16c1a63

Browse files
ak2j38ttasjwi
authored andcommitted
add : BOJ 1068 트리 풀이 추가
1. 트리 문제 풀이 추가 end
1 parent 74c6920 commit 16c1a63

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/아더/BOJ_1068_트리.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package 아더;
2+
3+
import java.io.*;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
public class BOJ_1068_트리 {
8+
static int N, DEL;
9+
static List<Integer>[] adj;
10+
11+
public static void main(String[] args) {
12+
try {
13+
input();
14+
delNodeAndChilderen(DEL);
15+
delNodeParents();
16+
solve();
17+
} catch (IOException e) {
18+
e.printStackTrace();
19+
}
20+
}
21+
22+
static void delNodeParents() {
23+
// 자식으로 남아있는 것 지우기
24+
for (List<Integer> a : adj) {
25+
if (a == null) continue;
26+
27+
if (a.contains(DEL)) {
28+
a.remove(Integer.valueOf(DEL));
29+
}
30+
}
31+
}
32+
33+
static void delNodeAndChilderen(int delNode) {
34+
// 해당 노드가 지워지면 자식노드들도 전부 삭제된다
35+
for (int node : adj[delNode]) {
36+
delNodeAndChilderen(node);
37+
}
38+
adj[delNode] = null;
39+
}
40+
41+
static void solve() {
42+
// 단말 노드의 갯수를 세야한다.
43+
int leafNodeCnt = 0;
44+
for (int i = 0; i < N; i++) {
45+
if (adj[i] == null) continue;
46+
if (adj[i].size() == 0) leafNodeCnt++;
47+
}
48+
System.out.println(leafNodeCnt);
49+
}
50+
51+
static void input() throws IOException {
52+
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
53+
BufferedReader br = new BufferedReader(new FileReader(new File("/Users/woo-jinpark/Desktop/Park/05_Test/input/input.txt")));
54+
55+
N = Integer.parseInt(br.readLine());
56+
adj = new ArrayList[N];
57+
58+
for (int i = 0; i < N; i++) {
59+
adj[i] = new ArrayList<>();
60+
}
61+
62+
String[] split = br.readLine().split(" ");
63+
for (int i = 0; i < N; i++) {
64+
int iNum = Integer.parseInt(split[i]);
65+
// 루트노드 확인
66+
if (iNum == -1) continue;
67+
// 부모의 값에 index 넣기
68+
adj[iNum].add(i);
69+
}
70+
DEL = Integer.parseInt(br.readLine());
71+
}
72+
}

0 commit comments

Comments
 (0)