1020 Tree Traversals (25分)(树的构造:后序+中序->层序)

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072

题意

给出后序+中序,输出层序

Sample Input:

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

Sample Output:

4 1 6 3 5 7 2

code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
pair<int,int> tree[40];
int post[40],in[40];
void create(int a,int b,int c,int d)
{
    if(a>=b) return ;//不再有子树,停止

    int i;
    for(i=c;i<=d;++i) if(in[i]==post[b]) break;
    //一定要注意if()中的情况
    if(i!=c) {
        tree[b].first=a+(i-c)-1;
        create(a,tree[b].first,c,i-1);
    }
    if(i!=d) {
        tree[b].second=b-1;
        create(b-1-(d-i-1),b-1,i+1,d);
    }

}
int main()
{
    int n; cin>>n;
    for(int i=1;i<=n;++i) cin>>post[i];
    for(int i=1;i<=n;++i) cin>>in[i];
    create(1,n,1,n);

    queue<int>Q;
    Q.push(n);
    cout<<post[n];
    while(!Q.empty())
    {
        int t=Q.front();
        Q.pop();
        if(tree[t].first!=0) Q.push(tree[t].first);
        if(tree[t].second!=0) Q.push(tree[t].second);
        if(t!=n) cout<<" "<<post[t];
    }
    return 0;
}
原文地址:https://www.cnblogs.com/liuyongliu/p/13512264.html