1020 Tree Traversals (25 分)

版权声明:本文为博主原创文章,欢迎交流学习,未经博主允许不得转载。 https://blog.csdn.net/qq_43749739/article/details/89856866

注:备战2020ing…暂时没时间注解啦,大家凑合先看下代码叭,肥宅对不住了。

#include <cstdio>
#include <queue>
using namespace std;
typedef struct
{
    int l, r;
}order;
int main()
{
    int N, m, cnt = 0;
    queue<order> q;
    scanf("%d", &N);
    order p = {0, N - 1} , i = {0, N - 1}, t;
    int in[N], post[N], ans[N];
    for(int i = 0; i < N; ++i)
        scanf("%d", &post[i]);
    for(int i = 0; i < N; ++i)
        scanf("%d", &in[i]);
    q.push(p);
    q.push(i);
    while( !q.empty() )
    {
        p = q.front();  q.pop();
        i = q.front();  q.pop();
        if( p.l == p.r )
            ans[cnt++] = post[p.l];
        else if( p.l < p.r )
        {
            ans[cnt++] = post[p.r];
            for( m = 0; in[ m + i.l ] != post[ p.r ]; ++m );
            t.l = p.l;  t.r = p.l + m - 1;   q.push(t);
            t.l = i.l;  t.r = i.l + m - 1;   q.push(t);
            t.l = p.l + m;   t.r = p.r - 1;  q.push(t);
            t.l = i.l + m + 1;  t.r = i.r;   q.push(t);
        }
    }
    for( int i = 0; i < cnt; ++i )
        printf("%d%s", ans[i], i == cnt-1 ? "":" ");
}

猜你喜欢

转载自blog.csdn.net/qq_43749739/article/details/89856866