uva 548 tree

这题就是运用了二叉树重建, 以及遍历。
二叉树的遍历:先序遍历,中序遍历,后序遍历
只要有一个中序序列再加上另一个序列就可唯一地重建原来二叉树。

进行了二叉树重建之后,只要对这棵二叉树进行搜索, 取得各个路径之和,然后找出最小的那个和即可。

//  Created by Chenhongwei in 2015.
//  Copyright (c) 2015 Chenhongwei. All rights reserved.

#include"iostream"
#include"cstdio"
#include"cstdlib"
#include"cstring"
#include"climits"
#include"queue"
#include"cmath"
#include"map"
#include"set"
#include"vector"
#include"sstream"
#include"algorithm"
using namespace std;
typedef long long ll;
const int maxn=10010;
int in[maxn],post[maxn],lch[maxn],rch[maxn],n;
int ans=INT_MAX,ansp=INT_MAX;
bool read(int* a)
{
	string s;
	if(!getline(cin,s))return false;
	stringstream ss(s);
	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;
	int root=post[r2];
	int p=l1;
	while(in[p]!=root)p++;
	int cnt=p-l1;
	lch[root]=build(l1,p-1,l2,l2+cnt-1);
	rch[root]=build(p+1,r1,l2+cnt,r2-1);
	return root;
}
void dfs(int u,int sum)
{
	sum+=u;
	if(!lch[u]&&!rch[u])
	{
		if(sum<ans||(sum==ans&&u<ansp))
		{
			ansp=u;
			ans=sum;
		}
	}
	if(lch[u])dfs(lch[u],sum);
	if(rch[u])dfs(rch[u],sum);
}
int main()
{	
	//ios::sync_with_stdio(false);
	// freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	while(read(in))
	{
		read(post);
		ans=INT_MAX,ansp=INT_MAX;
		build(0,n-1,0,n-1);
		dfs(post[n-1],0);
		cout<<ansp<<endl;

	}
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值