PAT Advanced Level 1102二叉树反转

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
int lch[12],rch[12],in[12],t1,t2,vis[12];
void inorder(int root)
{
    if(root==-1)
        return ;
    inorder(lch[root]);
    in[t1++]=root;
    inorder(rch[root]);
}
void cengorder(int root)
{
    queue<int> q;
    q.push(root);
    while(!q.empty())
    {
        int r = q.front();
        q.pop();
        cout<<r;
        if(lch[r]!=-1)
        q.push(lch[r]);
        if(rch[r]!=-1)
        q.push(rch[r]);
        if(q.size()!=0)
        {
            cout<<" ";
        }
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        char a,b;
        cin>>a>>b;
        if(a=='-')
            lch[i]=-1;
        else
            lch[i]=a-'0';
        if(b=='-')
            rch[i]=-1;
        else
            rch[i]=b-'0';
        vis[lch[i]]=1;
        vis[rch[i]]=1;
    }
    for(int i=0;i<n;i++)
    {
        swap(lch[i],rch[i]);
    }
    int root;
    for(int i=0; i<n; i++)
    {
        if(!vis[i])
        {
            root=i;
            break;
        }
    }
  /*  cout<<root<<endl;
    for(int i=0;i<n;i++)
    {
        cout<<lch[i]<<" ";
    }
    cout<<endl;
    for(int i=0;i<n;i++)
    {
        cout<<rch[i]<<" ";
    }
    cout<<endl;*/
    cengorder(root);
    cout<<endl;
    inorder(root);
    for(int i=0;i<n;i++)
    {
        cout<<in[i];
        if(i!=n-1)
        {
            cout<<" ";
        }
    }

    return 0;
}
/*
1 -
- -
0 -
2 7
- -
- -
5 -
4 6*/

 

posted @ 2018-08-26 15:11  MCQ  阅读(106)  评论(0编辑  收藏  举报