Tree UVA - 548(建树+dfs)

在这里插入图片描述
题目大意:
给你中序遍历序列和后序遍历序列,要你找出这棵树中从根节点到任意叶子节点的最小值中的叶子节点的值。
难点:
输入,建树
学到两个不错的技巧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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值