根据后序中序输出树并且求解路径权值和最小的叶子结点

题目描述:

  给一颗点带权(权值均为正整数并且小于10000)的二叉树的中序和后序遍历,找一个叶子是的它到根的路径上的权和最小。如果有多解,输出叶子权最小的那个。

输入样例两行, 第一行为中序遍历,第二行为后序遍历,输出叶子结点。

样例输入:

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

样例输出:

1

3

分析:先构建树在利用bfs统计路径权值和最小的即可,利用树的中序和后序序列来建树是一个递归的过程,数据结构都学过,就不赘述可,看代码,很清楚:

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

const int maxn = 10000 +5;
int in_order[maxn],post_order[maxn],lch[maxn],rch[maxn];
int n,best,best_sum;

bool readList(int* a){
	string line;
	if(!getline(cin,line)) return false;
	stringstream ss(line);//字符串流 
	n = 0;
	int x;
	while(ss>>x) a[n++] = x;//将值写入x所指的类型,并且以空格分隔 
	return n > 0;
}
int build(int L1,int R1,int L2,int R2){
	if(L1 > R1) return 0;//空树,即叶子结点 
	int root  = post_order[R2]; 
	int p = L1;
	while(in_order[p] != root) p++;
	int cnt = p - L1;
	lch[root] = build(L1,p-1,L2,L2+cnt-1);//左子树 ,所以可知叶子结点的lch和rch均为0 
	rch[root] = build(p+1,R1,L2+cnt,R2-1);//右子树 	
	return root;
}
int dfs(int u,int sum){
     sum += u;
	 if(!lch[u]&&!rch[u]){//到了叶子结点开始判断 
	 	if(sum < best_sum||(sum == best_sum&&u < best)){
	 		best_sum = sum;
	 		best = u;
		 }		     
	 }
	 if(lch[u])	dfs(lch[u],sum);
	 if(rch[u]) dfs(rch[u],sum);
}
int main(){
	
   while(readList(in_order)){
   	   readList(post_order);
   	   best_sum = 1000000000;
   	   build(0,n-1,0,n-1,0);
//   	   for(int i = 0;i < n;i++){//查看建树之后的叶子结点 
//   	   	int u = in_order[i];
//   	   	if(!lch[u]&&!rch[u])
//   	   	   cout<<u<<endl;
//	   }  	     
   	   
   	   dfs(post_order[n-1],0);
   	   cout<< best << endl;
   }
	return 0;	
}



猜你喜欢

转载自blog.csdn.net/JingleLiA/article/details/80601029