boj)1991 - 트리 순회
2020. 12. 11. 14:43ㆍPS/boj
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
58
59
60
61
62
63
64
65
66
67
|
import java.io.*;
import java.util.StringTokenizer;
public class boj_1991 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int n;
static Node[] a;
public static void main(String[] args) throws IOException {
n = Integer.parseInt(br.readLine());
a = new Node[n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int x = st.nextToken().charAt(0) - 'A';
char y = st.nextToken().charAt(0);
char z = st.nextToken().charAt(0);
int left = -1;
int right = -1;
if (y != '.') {
left = y - 'A';
}
if (z != '.') {
right = z - 'A';
}
a[x] = new Node(left, right);
}
preorder(0);
System.out.println();
inorder(0);
System.out.println();
postorder(0);
System.out.println();
}
static void preorder(int x) {
if (x == -1) return;
System.out.print((char)(x + 'A'));
preorder(a[x].left);
preorder(a[x].right);
}
static void inorder(int x) {
if (x == -1) return;
inorder(a[x].left);
System.out.print((char)(x + 'A'));
inorder(a[x].right);
}
static void postorder(int x) {
if (x == -1) return;
postorder(a[x].left);
postorder(a[x].right);
System.out.print((char)(x + 'A'));
}
}
class Node {
int left;
int right;
public Node(int left, int right) {
this.left = left;
this.right = right;
}
}
|
cs |
- 트리
- 전위순회, 중위순회, 후위순회를 구현
- 그냥 이론상으로만 아는걸 코드로 구현해보려고 하니깐 어렵다.
'PS > boj' 카테고리의 다른 글
BOJ)15686 - 치킨배달 (0) | 2022.09.22 |
---|---|
boj)2250 - 트리의 높이와 너비 (0) | 2020.12.12 |
boj)7562 - 나이트의 이동 (0) | 2020.12.10 |
boj)11723 - 집합 (0) | 2020.12.09 |
boj)14391 - 종이 조각 (0) | 2020.12.09 |