/
alds1_7c.cpp
71 lines (64 loc) · 1.44 KB
/
alds1_7c.cpp
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
// ALDS1 7_C
// C++14
#include <bits/stdc++.h>
using namespace std;
// 二分木の巡回
struct Node {
int parent;
int left;
int right;
};
vector<Node> T;
const int NIL = -1; // null
// 先行順巡回 (根節点、左部分木、右部分木の順)
void preParse(int node) {
if (node == NIL) return;
cout << " " << node;
preParse(T.at(node).left);
preParse(T.at(node).right);
}
// 中間順巡回 (左部分木、根節点、右部分木の順)
void inParse(int node) {
if (node == NIL) return;
inParse(T.at(node).left);
cout << " " << node;
inParse(T.at(node).right);
}
// 後行順巡回 (左部分木、右部分木、根節点の順)
void postParse(int node) {
if (node == NIL) return;
postParse(T.at(node).left);
postParse(T.at(node).right);
cout << " " << node;
}
int main() {
int N; cin >> N;
T.resize(N);
// 初期化
for (int i = 0; i < N; i++) {
T.at(i).parent = NIL;
T.at(i).left = NIL;
T.at(i).right = NIL;
}
for (int i = 0; i < N; i++) {
int id, l, r;
cin >> id >> l >> r;
T.at(id).left = l;
T.at(id).right = r;
if (l != NIL) T.at(l).parent = id;
if (r != NIL) T.at(r).parent = id;
}
int root = NIL;
for (int i = 0; i < N; i++) {
if (T.at(i).parent == NIL) root = i;
}
cout << "Preorder" << endl;
preParse(root);
cout << endl;
cout << "Inorder" << endl;
inParse(root);
cout << endl;
cout << "Postorder" << endl;
postParse(root);
cout << endl;
}