首先根据中序遍历和后序遍历递归地构造二叉树(后续遍历的最后一个节点为二叉树的根节点),然后前序遍历。
输入有点坑,你说你直接告诉多少个节点多好。。。我想的是先用fets读取整个串,然后用atoi转化为数字,本地运行没问题可是一提交就报错,暂时还没找到原因,大概是因为回车符的问题,参考了别人的输入方法过了,比我的想法要好。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000 + 5;
char s[maxn*3];
int W,WS;
struct node{
int num = -1;
struct node* left = NULL;
struct node* right = NULL;
};
node* newnode(){ return new node; }
node* build_tree(int n,int mid[],int late[]){
if(!n) return NULL;
node* root = new node;
int rp = 0;
root->num = late[n-1];
while(mid[rp] != late[n-1]) rp++; //find the position of root node in the mid
root->left = build_tree(rp,mid,late);
root->right = build_tree(n-rp-1,mid+rp+1,late+rp);
return root;
}
void pre_travel(node* root,int t){
t += root->num;
if(!root->left && !root->right){
if(t < WS){ WS = t; W = root->num; }
else if(t == WS && root->num < W) W = root->num;
return;
}
if(root->left) pre_travel(root->left,t);
if(root->right) pre_travel(root->right,t);
}
int main(){
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
int mid[maxn],late[maxn];
/* Runtime Error... maybe because of fgets
while(fgets(s,maxn*3,stdin)){
int n = 0,i = 0,len = strlen(s);
for(;;){
while(!isdigit(s[i])) i++;
if(i >= len) break;
mid[n++] = atoi(s+i);
while(isdigit(s[i])) i++;
}
for(int i = 0;i < n;i++) scanf("%d",&late[i]);
node* root = build_tree(n,mid,late);
W = 1<<30,WS = 1<<30;
pre_travel(root,0);
printf("%d\n",W);
getchar(); //吃掉第二行的回车!!!
}*/
char ch;
while(~ scanf("%d%c", &mid[0], &ch))
{
int n = 1;
for(int i = 1; ch != '\n'; i++)
scanf("%d%c", mid + i, &ch), n++;
ch = ' ';
for(int i = 0; ch != '\n'; i++)
scanf("%d%c", late + i, &ch);
node* root = build_tree(n,mid,late);
W = 1<<30,WS = 1<<30;
pre_travel(root,0);
printf("%d\n",W);
}
return 0;
}