-
Notifications
You must be signed in to change notification settings - Fork 2
/
1042.cpp
70 lines (61 loc) · 1.26 KB
/
1042.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
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAX_N = 12350;
struct node {
int lson = 0, rbro = 0;
};
node a[MAX_N];
void preorder(int t) {
cout << t << " ";
if (a[t].lson) preorder(a[t].lson);
if (a[t].rbro) preorder(a[t].rbro);
}
void postorder(int t) {
if (a[t].lson) postorder(a[t].lson);
cout << t << " ";
if (a[t].rbro) postorder(a[t].rbro);
}
void level(queue<int> t) {
queue<int> next;
while (!next.empty()) next.pop();
while (!t.empty()) {
int temp = t.front();
t.pop(); cout << temp << " ";
if (a[temp].lson) {
next.push(a[temp].lson);
int temp2 = a[a[temp].lson].rbro;
while (temp2) {
next.push(temp2);
temp2 = a[temp2].rbro;
}
}
}
if (!next.empty()) level(next);
}
int main() {
ios::sync_with_stdio(false);
int n; cin >> n;
int pre[MAX_N]; memset(pre, 0, sizeof(pre));
for (int i = 1; i <= n; ++i) {
int temp, lson, rbro;
cin >> temp >> lson >> rbro;
a[temp].lson = lson;
a[temp].rbro = rbro;
pre[lson] = temp;
if (rbro) {
pre[rbro] = pre[temp] = -1;
}
}
int root;
for (root = 1; root <= n; ++root) if (pre[root] == 0) break;
preorder(root);
cout << endl;
postorder(root);
cout << endl;
queue<int> p; p.push(root);
level(p);
cout << endl;
return 0;
}