PAT (Advanced Level) 1102. Invert a Binary Tree (25)

简单题。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

struct Node
{
    int left;
    int right;
}s[20];
int n;
vector<int>ans1,ans2;
int flag[20];
int root;

void bfs()
{
    queue<int>q; q.push(root);
    while(!q.empty())
    {
        int h=q.front(); q.pop();
        ans1.push_back(h);
        if(s[h].left!=-1) q.push(s[h].left);
        if(s[h].right!=-1) q.push(s[h].right);
    }
}

void dfs(int x)
{
    if(s[x].left!=-1) dfs(s[x].left);
    ans2.push_back(x);
    if(s[x].right!=-1) dfs(s[x].right);
}

int main()
{
    memset(flag,0,sizeof flag);
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        char L[5],R[5];
        scanf("%s%s",L,R);
        if(L[0]=='-') s[i].left=-1;
        else
        {
            s[i].left=L[0]-'0';
            flag[L[0]-'0']=1;
        }
        if(R[0]=='-') s[i].right=-1;
        else
        {
            s[i].right=R[0]-'0';
            flag[R[0]-'0']=1;
        }
    }

    for(int i=0;i<n;i++)
        if(flag[i]==0) root=i;

    for(int i=0;i<n;i++)
        swap(s[i].left,s[i].right);

    bfs();
    dfs(root);
    for(int i=0;i<ans1.size();i++)
    {
        printf("%d",ans1[i]);
        if(i<ans1.size()-1) printf(" ");
        else printf("\n");
    }

    for(int i=0;i<ans1.size();i++)
    {
        printf("%d",ans2[i]);
        if(i<ans2.size()-1) printf(" ");
        else printf("\n");
    }

    return 0;
}

 

posted @ 2016-07-05 08:57  Fighting_Heart  阅读(156)  评论(0编辑  收藏  举报