题目大意:
给你中序遍历序列和后序遍历序列,要你找出这棵树中从根节点到任意叶子节点的最小值中的叶子节点的值。
难点:
输入,建树
学到两个不错的技巧or函数?
if(!getline(cin,line))return false;//getline(cin,str)可以将空格作为字符串读入 ,并且当读到文件尾返回0
stringstream ss(line);//文件流
while(ss>>x)//自动过滤字符串中的空格赋值
a[n++]=x;

代码:

#include<iostream>
#include<sstream>
#include<string>
#include<cstring>
using namespace std;

//getline()读到文件尾返回0 
const int inf=0x3f3f3f3f;
const int maxn=1e4+10;
int in_order[maxn],post_order[maxn],l[maxn],r[maxn];
int n,sum_best,best;
bool read_list(int a[]){
	string line;
	if(!getline(cin,line))return false;//getline(cin,str)可以将空格作为字符串读入 
	stringstream ss(line);//文件流 
	n=0;
	int x;
	while(ss>>x)//自动过滤字符串中的空格 
	a[n++]=x;
	return n>0;
}
int build(int r1,int r2,int t1,int t2){
	if(r1>r2)return 0;
	int root=post_order[t2];
	int k=r1;
	while(in_order[k]!=root)k++;
	int cnt=k-r1;//左子树节点个数 
	l[root]=build(r1,k-1,t1,t1+cnt-1);
	r[root]=build(k+1,r2,t1+cnt,t2-1);
	return root;
}
/* 3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255 */
void dfs(int u,int sum){
	sum+=u;
	if((l[u]==0&&r[u]==0)&&(sum<sum_best||(sum==sum_best&&u<best))){
		best=u;
		sum_best=sum;
		return ;
	}
	if(l[u]){
		dfs(l[u],sum);
	}
	if(r[u]){
		dfs(r[u],sum);
	}
}
int main(){
	while(read_list(in_order)){
		read_list(post_order);
		build(0,n-1,0,n-1);
		sum_best=inf;
		dfs(post_order[n-1],0);
		cout<<best<<endl;
	}
}