刚开始看题,觉得怎么考这么简单的题。。
然后一看N 50000 就知道是个大坑了. 建树是不行的.时间会超,递归到第一个值就可以了
#include <iostream>
#include <cstring>
#include <climits>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#define MAX 50010
using namespace std;
int n;
int pre[MAX];
int in[MAX];
int post[MAX];
int pp = 0;
struct node{
node * l,* r;
int data;
node(){l = r = NULL;};
};
typedef node * tree;
bool isFind = false;
tree buildTree(int pl,int ph, int il,int ih,tree t){
if(!isFind && pl <= ph){
t = new node;
t->data = pre[pl];
int pos = -1;
for(int i = il ;i <= ih;i++){
if(in[i] == pre[pl]){
pos = i;
break;
}
}
if(pos == -1)
return NULL;
else{
t->l = buildTree(pl+1,pl+pos-il,il,pos-1,t->l);
t->r = buildTree(pl+pos-il+1,ph,pos+1,ih,t->r);
post[pp++] = t->data;
if(pp == 1)
isFind = true;
}
}
return t;
}
int main(){
scanf("%d",&n);
for(int i = 0 ;i < n ;i++){
scanf("%d",&pre[i]);
}
for(int i = 0 ;i < n ;i++){
scanf("%d",&in[i]);
}
tree t = NULL;
t=buildTree(0,n-1,0,n-1,t);
// postorder(t);
cout << post[0] << endl;
return 0;
}