这题就是运用了二叉树重建, 以及遍历。
二叉树的遍历:先序遍历,中序遍历,后序遍历
只要有一个中序序列再加上另一个序列就可唯一地重建原来二叉树。
二叉树的遍历:先序遍历,中序遍历,后序遍历
只要有一个中序序列再加上另一个序列就可唯一地重建原来二叉树。
进行了二叉树重建之后,只要对这棵二叉树进行搜索, 取得各个路径之和,然后找出最小的那个和即可。
// 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;
}