PAT 1020
题意
给出后序遍历,及中序遍历,求层序遍历。
节点个数N<=30
注意点
卡了一个段错误,虽说30很小,但如果是一条长链的话,2的30次方,用数组要炸。
所以用vector存一下吧。
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <stack>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 1e3+50;
const double eps = 1.e-8;
int n, tree[300], post[50], in[50];
struct node {
int index;
int val;
};
vector<node> ans;
bool cmp (node aa, node bb) {
return aa.index < bb.index;
}
void build(int root, int start, int end, int th) {
if (start > end) return ;
//tree[th] = post[root]; //一开始用了这个出现段错误,题目虽然给出N<=30.但是如果这棵树是一条链,那么数组要开2的30次方,肯定就超过了我所开的300的空间!!!
ans.push_back({th, post[root]});
int i = start;
while (post[root] != in[i] && i < end) i++;
int len = end - i;//right numbers
build(root-len-1, start, i-1, th*2+1);
build(root-1, i+1, end, th*2+2);
}
void print(){
for (int i = 0; i < n; i++) {
printf("%d%c", tree[i], i == n-1 ? '\n' : ' ');
}
}
int main( ){
cin>>n;
for (int i = 0; i < n; i++) {
cin>>post[i];
}
for (int i = 0; i < n; i++) {
cin>>in[i];
}
build(n-1,0,n-1,0);
//print();
sort(ans.begin(), ans.end(), cmp);
for (int i = 0; i < ans.size(); i++) {
if (i != 0) cout<<" ";
cout<<ans[i].val;
}
return 0;
}