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

Posted Fighting Heart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于PAT (Advanced Level) 1102. Invert a Binary Tree (25)的主要内容,如果未能解决你的问题,请参考以下文章

1102. Invert a Binary Tree (25)二叉树——PAT (Advanced Level) Practise

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

PAT Advanced 1102 Invert a Binary Tree (25分)

PAT (Advanced Level) 1025. PAT Ranking (25)

PAT Advanced Level 1044

PAT Advanced Level 1043