【日常学习】【二叉树遍历】Uva548 - Tree题解

这道题目本身不难,给出后序遍历和中序遍历,求到节点最小路径的叶子,相同长度就输出权值小的叶子。

Uva上不去了,没法测。基本上是按照ruka的代码来的。直接上代码

//Uva548 Tree
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<cctype>
using namespace std;

const int maxv=10000+10;
int inorder[maxv],postorder[maxv],l[maxv],r[maxv];
int n;
int best,best_num;

bool read_list(int *a){
	string line;
	if (!getline(cin,line)) return false;
	stringstream ss(line);
	n=0;
	int x;
	while (ss>>x) a[n++]=x;
	return n>0;
}

int build(int l1,int r1,int l2,int r2){
	if (l1>r1) return 0;//notice
	int root=postorder[r2];
	int p=0;
	while (inorder[p]!=root) p++;
	int cnt=p-l1;
	l[root]=build(l1,p-1,l2,l2+cnt-1);
	r[root]=build(p+1,r1,l2+cnt,r2-1);
	return root;
}

void dfs(int now,int sum){
	sum+=now;
	if ((!l[now])&&(!r[now])){
		if ((sum<best_num)||((sum==best_num)&&(now<best))){
			best=now;
			best_num=sum;
		}
	}
	if (l[now]) dfs(l[now],sum);
	if (r[now]) dfs(r[now],sum);
} 

int main(){
	freopen("1.txt","r",stdin);
	freopen("2.txt","w",stdout);
	while (read_list(inorder)){//every time you read an inorder
		read_list(postorder);
		build(0,n-1,0,n-1);//build a tree
		best_num=1000000000;
		dfs(postorder[n-1],0);
		cout<<best<<endl;;
	}
	return 0;
} 

五一又要出去培训了,要求相当高,我要抓紧时间学习了。

——长风破浪会有时,直挂云帆济沧海

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值