玩转二叉树

7-11 玩转二叉树 (25 分)
 
 给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

input:

7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

output:
4 6 1 7 5 3 2

 

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<queue>
#include<cmath>
#include<vector>
#include<cstdlib>
using namespace std;

#define long long ll
const int maxn  = 100 + 5;

int zhong[maxn],qian[maxn];
struct node
{
    int l,r;
}a[maxn];
int build(int la,int ra,int lb,int rb)
{
    if(la > ra)
        return 0;
    int rt = qian[lb];
    int posrt = la;
    while(zhong[posrt] != rt)
        posrt++;
    int l = posrt - la;
    a[rt].l = build(la,la + l - 1,lb + 1,lb + l);
    a[rt].r = build(posrt + 1,ra,lb + l + 1,rb);
    return rt;
}
void bfs(int x)
{
    queue<int>que;
    vector<int>vec;
    que.push(x);
    while(!que.empty())
    {
        int tmp = que.front();
        que.pop();
        if(tmp == 0)
            break;
        vec.push_back(tmp);
        if(a[tmp].r != 0)
            que.push(a[tmp].r);
        if(a[tmp].l != 0)
            que.push(a[tmp].l);
    }
    for(int i=0;i<vec.size();i++)
        printf("%d%c",vec[i],i == (vec.size() - 1) ? '\n' : ' ');
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&zhong[i]);
    for(int i=1;i<=n;i++)
        scanf("%d",&qian[i]);
    build(1,n,1,n);
    int root = qian[1];
    bfs(root);
}

 

posted @ 2019-03-20 23:56  千摆渡Qbd  阅读(323)  评论(0编辑  收藏  举报