PAT

L2-011. 玩转二叉树

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

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

输入格式:

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

输出格式:

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

输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
#include <iostream>
#include <queue>
using namespace std;
/***************************************************************************************************************
    思路:
        1,利用分冶创建二叉树(又花了一点时间理解 L1,R1,L2,R2)
        2,利用 BFS 输出,因为题意是镜像,先将右孩子入队列,再将左孩子入队列即可
***************************************************************************************************************/

int inorder[35],outorder[35];
int lch[35],rch[35];

int build(int L1,int R1,int L2,int R2){
    if(L1 > R1) return 0;
    int root = outorder[L2];

    int p = L1;
    while(inorder[p] != root)   p++;
    int cnt = p-L1;

    lch[root] = build(L1,p-1,L2+1,L2+cnt);
    rch[root] = build(p+1,R1,L2+cnt+1,R2);

    return root;
}
void bfs(int root){
    queue<int> Q;
    int temp;
    int flag = 0;
    Q.push(root);
    while(!Q.empty()){
        temp = Q.front();
        Q.pop();

        if(flag)    cout<<" ";
        cout<<temp;
        flag = 1;

        if(rch[temp])   Q.push(rch[temp]);
        if(lch[temp])   Q.push(lch[temp]);
    }
    cout<<endl;
}
int main()
{
    int n;
    while(cin>>n){
        for(int i = 0;i < n;i ++)   cin>>inorder[i];
        for(int i = 0;i < n;i ++)   cin>>outorder[i];
        build(0,n-1,0,n-1);
        bfs(outorder[0]);
    }
    return 0;
}


原文地址:https://www.cnblogs.com/Jstyle-continue/p/6351952.html