二叉树的遍历

题目

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
#include <iostream>
#include <queue>
using namespace std;
struct ty
{
int z, y;
}a[500005];
int vis[500005];
void xian(int f)
{
cout << f << ' ';
if (a[f].z) xian(a[f].z);
if (a[f].y) xian(a[f].y);
return ;
}
void zhong (int f)
{
if (a[f].z) zhong(a[f].z);
cout << f << ' ';
if (a[f].y) zhong(a[f].y);
return ;
}
void hou(int f)
{
if (a[f].z) hou(a[f].z);
if (a[f].y) hou(a[f].y);
cout << f << ' ';
return ;
}
void ceng(int f)
{
queue<int> q;
q.push(f);
while (q.size())
{
int y = q.front();
q.pop();
cout << y << ' ';
if (a[y].z) q.push(a[y].z);
if (a[y].y) q.push(a[y].y);
}
return ;
}
int main()
{
int n;
cin >> n;
int f = 0;
for (int i = 1; i < n; i++)
{
int u, v, op;
cin >> u >> v >> op;
vis[u] = 1;
if (op == 0) a[v].z = u;
else a[v].y = u;
}
for (int i = 1; i < n; i++)
if (vis[i] == 0) f = i;
xian(f);
cout << endl;
zhong(f);
cout << endl;
hou(f);
cout << endl;
ceng(f);
return 0;
}