PAT A1020

PAT A1020

标签(空格分隔): PAT


#include <cstdio>
#include <queue>
using namespace std;

const int maxn = 100;
int pos[maxn], in[maxn];
int n;

struct node {
    int data;
    node* lchild;
    node* rchild;
};

node* create(int inL, int inR, int posL, int posR) {
    if(posL > posR) return NULL;
    node* root = new node;
    root->data = pos[posR];
    int k;
    for(k = inL; k <= inR; k++) {
        if(pos[posR] == in[k])
            break;
    }
    int numberLeft = k - inL;
    root->lchild = create(inL, inL + numberLeft - 1, posL, posL + numberLeft - 1);
    root->rchild = create(inL + numberLeft + 1, inR, posL + numberLeft, posR - 1);
    return root;
}

int cnt = 0;     //坑
void print(node* root) {
    queue<node*> q;
    q.push(root);
    while(!q.empty()) {
        node* now = q.front();
        q.pop();
        printf("%d", now->data);
        cnt++;
        if(cnt < n) printf(" ");
        if(now->lchild != NULL) q.push(now->lchild);
        if(now->rchild != NULL) q.push(now->rchild);
    }
}

int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &pos[i]);
    }
    for(int i = 1; i <= n; i++) {
        scanf("%d", &in[i]);
    }
    node* ans = new node;
    ans = create(1, n, 1, n);
    print(ans);
    return 0;
}

原文地址:https://www.cnblogs.com/Kirarrr/p/10431731.html