1102 Invert a Binary Tree (25 分)
水~。
\(N \le 10\),结点下标的范围为\(0 \sim 9\),所以直接和字符'0'相减即可。
const int N=35;
PII tree[N];
int fa[N];
vector<int> layer,in;
int n;
void bfs(int root)
{
queue<int> q;
q.push(root);
while(q.size())
{
int t=q.front();
q.pop();
layer.pb(t);
if(~tree[t].se) q.push(tree[t].se);
if(~tree[t].fi) q.push(tree[t].fi);
}
}
void preorder_invert(int root)
{
if(root == -1) return;
preorder_invert(tree[root].se);
in.pb(root);
preorder_invert(tree[root].fi);
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
char a,b;
cin>>a>>b;
if(a != '-') tree[i].fi=a-'0',fa[a-'0']=i;
else tree[i].fi=-1;
if(b != '-') tree[i].se=b-'0',fa[b-'0']=i;
else tree[i].se=-1;
}
int root=0;
while(fa[root] != 0)
root=fa[root];
bfs(root);
preorder_invert(root);
for(int i=0;i<layer.size();i++)
if(i) cout<<' '<<layer[i];
else cout<<layer[i];
cout<<endl;
for(int i=0;i<in.size();i++)
if(i) cout<<' '<<in[i];
else cout<<in[i];
cout<<endl;
//system("pause");
return 0;
}