自用资料
#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int n;
int l[N];
int r[N];
int in[N];
int get(char a)
{
if(a == '-') return -1;
else return a - '0';
}
void dfs(int u)
{
if(u == -1) return;
dfs(r[u]);
cout << u << " ";
dfs(l[u]);
}
void bfs(int root)
{
queue<int> q;
q.push(root);
while(q.size())
{
int t = q.front();
cout << t << " ";
q.pop();
if(r[t] != -1) q.push(r[t]);
if(l[t] != -1) q.push(l[t]);
}
}
int main()
{
cin >> n;
for(int i = 0;i < n;i ++)
{
char a, b;
cin >> a >> b;
l[i] = get(a);
r[i] = get(b);
in[get(a)] ++;
in[get(b)] ++;
}
int root;
for(int i = 0;i < n;i ++)
{
if(in[i] == 0 and (l[i] != -1 or r[i] != -1))
{
root = i;
break;
}
}
bfs(root);
cout << endl;
dfs(root);
}