트리 순회 [실버 1]
문제 링크
https://www.acmicpc.net/problem/1991
풀이
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<iostream>
using namespace std;
int N;
typedef struct node {
char left;
char right;
}node;
node tree[26];
int cnt[26];
void preorder(int idx) {
// print current
cout << char('A' + idx);
// left
if (tree[idx].left != '.') {
preorder(tree[idx].left - 'A');
}
// right
if (tree[idx].right != '.') {
preorder(tree[idx].right - 'A');
}
}
void inorder(int idx) {
// left
if (tree[idx].left != '.') {
inorder(tree[idx].left - 'A');
}
// print current
cout << char('A' + idx);
// right
if (tree[idx].right != '.') {
inorder(tree[idx].right - 'A');
}
}
void postorder(int idx) {
// left
if (tree[idx].left != '.') {
postorder(tree[idx].left - 'A');
}
// right
if (tree[idx].right != '.') {
postorder(tree[idx].right - 'A');
}
// print current
cout << char('A' + idx);
}
int main(void)
{
cin >> N;
char parent, left, right;
for (int i = 0; i < N; i++)
{
cin >> parent >> left >> right;
tree[parent - 'A'].left = left;
tree[parent - 'A'].right = right;
cnt[parent - 'A']++;
}
int rootIdx = -1;
for (int i = 0; i < N; i++)
{
if (cnt[i] == 1) {
rootIdx = i;
break;
}
}
preorder(rootIdx);
cout << "\n";
inorder(rootIdx);
cout << "\n";
postorder(rootIdx);
return 0;
}