-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path트리의 부모 찾기.java
More file actions
57 lines (44 loc) · 1.47 KB
/
트리의 부모 찾기.java
File metadata and controls
57 lines (44 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static List<Integer>[] tree;
static int[] parent;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
tree = new ArrayList[n + 1];
parent = new int[n + 1];
for (int i = 1; i <= n; i++) {
tree[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
tree[a].add(b);
tree[b].add(a);
}
bfs(1);
StringBuilder sb = new StringBuilder();
for (int i = 2; i < n + 1; i++) {
sb.append(parent[i]).append("\n");
}
System.out.println(sb);
}
static void bfs(int root) {
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(root);
parent[root] = root;
while (!queue.isEmpty()) {
int curr = queue.poll();
for (int i : tree[curr]) {
if (parent[i] == 0) {
parent[i] = curr;
queue.offer(i);
}
}
}
}
}