欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

后序中序求层序

程序员文章站 2022-05-19 20:55:06
...
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <queue>
using namespace std;
const int NI = 50;
int n, post[NI], in[NI];
struct node {
    int num;
    struct node *left;
    struct node *right;
};
struct node *CreatNode(int n) {
    struct node *tmp = (struct node *)malloc(sizeof(struct node));
    tmp->num = n;
    tmp->left = tmp->right = NULL;
    return tmp;
}
struct node *BuildTree(int pl, int pr, int il, int ir) {
    if(pl > pr || il > ir) return NULL;
    struct node *root = CreatNode(post[pr]);
    int p;
    for(int i = il; i <= ir; i++) {
        if(in[i] == post[pr]) {
            p = i; break;
        }
    }
    root->left = BuildTree(pl, pl+p-il-1, il, p-1);
    root->right = BuildTree(pl+p-il, pr-1, p+1, ir);
    return root;
};
vector<int> v;
void bfs(struct node *root) {
    queue<struct node*> q;
    q.push(root);
    while(!q.empty()) {
        struct node *t = q.front();
        v.push_back(t->num);
        q.pop();
        if(t->left) q.push(t->left);
        if(t->right) q.push(t->right);
    }
}
int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &post[i]);
    }
    for(int i = 0; i < n; i++) {
        scanf("%d", &in[i]);
    }
    struct node *root = BuildTree(0, n-1, 0, n-1);
    bfs(root);
    printf("%d", v[0]);
    for(int i = 1; i < n; i++) {
        printf(" %d", v[i]);
    }
    printf("\n");
    return 0;
}