7-1 根据后序和中序遍历输出先序遍历 (25 分)

7-1 根据后序和中序遍历输出先序遍历 (25 分)

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。

输入格式:

第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

输出格式:

在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。

输入样例:

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

输出样例:

Preorder: 4 1 3 2 6 5 7
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <map>
#include <set>
#include <vector>
#include <cstring>
#include <queue>
#include <cmath>
#define FRER() freopen("in.txt","r",stdin);
#define FREW() freopen("out.txt","w",stdout);
#define mem(a,b) memset(a,b,sizeof(a));
#define go int T;scanf("%d",&T);for(int cas=1;cas<=T;cas++)
#define mod 1000000007
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const int maxn = 100 + 7 ;
int a[maxn],b[maxn],c[maxn],pos[maxn];
int tot,n;
void fuck(int l1,int r1,int l2,int r2){
    if(l1>r1) return;
    if(l2>r2) return;
    c[tot++] = a[r1];
    int len1 = pos[a[r1]] - l2;
    int len2 = r2 - pos[a[r1]];
    fuck(l1, l1+len1-1, l2, l2+len1-1);
    fuck(r1-len2, r1-1, pos[a[r1]]+1, pos[a[r1]]+len2);
}
int main(){
    //ios::sync_with_stdio(false);
    //FRER();
    tot = 1;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=n;i++) {scanf("%d",&b[i]);pos[b[i]] = i;}
    fuck(1,n,1,n);
    printf("Preorder: ");
    for(int i=1;i<=n;i++){
        printf("%d%c",c[i],i==n?'\n':' ');
    }
}

猜你喜欢

转载自blog.csdn.net/Insist_77/article/details/83794243