L2-011. 玩转二叉树

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

输入格式:

输入第一行给出一个正整数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<algorithm>
#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
#include<queue>
#include<cstring>
#include<string>
using namespace std;

const int N = 100 + 5;
int pre[N], in[N];

struct node{
    int key, lchild, rchild;
    node(){
        lchild = rchild = 0;
    }
}Tree[N];
int n, st;

void DFS(int &root, int ps, int pt, int is, int it){
    if(!root) root = ++st;
    Tree[root].key = pre[ps];
    int pos = is;
    while(in[pos] != pre[ps]) pos++;
    if(is != pos){
        DFS(Tree[root].lchild, ps + 1, ps + pos - is, is, pos - 1);
    }
    if(it != pos){
        DFS(Tree[root].rchild, ps + pos - is + 1, pt, pos + 1, it);
    }
}

void BFS(int root){
    queue<int> Q;
    int cnt = 0;
    Q.push(root);
    while(!Q.empty()){
        int tmp = Q.front(); Q.pop();
        printf("%d%c", Tree[tmp].key, (++cnt == n)?'
':' ');
        if(Tree[tmp].rchild)
            Q.push(Tree[tmp].rchild);

        if(Tree[tmp].lchild)
            Q.push(Tree[tmp].lchild);

    }
}
int main(){
    scanf("%d", &n);
    for(int i = 0; i < n; i++) scanf("%d", &in[i]);
    for(int i = 0; i < n; i++) scanf("%d", &pre[i]);

    int root = 0;
    st = 0;
    DFS(root, 0, n - 1, 0, n - 1);
    BFS(root);
}
原文地址:https://www.cnblogs.com/Pretty9/p/8624790.html