链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=489
好吧,这道题让我对二叉树已经基本熟悉了。通过给出的中序遍历和后序遍历来建立二叉树然后找到路径权值最小的叶。
如果存在路径权值相同的叶取叶权值最小的。
(给出前序遍历和中序遍历或者给出中序遍历和后续遍历都能建立一棵树,但是如果给出了前序遍历和后序遍历不能建立一棵确定的树,即存在多种建树的可能)
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<ctype.h>
#include<algorithm>
#include<string>
#define PI acos(-1.0)
#define maxn 100005
#define INF 1<<25
#define MAX 0x7fffffff
typedef long long ll;
using namespace std;
int ans=maxn;
int ii=0;
int pos=0;
int rec=0;
int Build(int *s1,int *s2,int zl,int zr,int hl,int hr)
{
int n=zr-zl+1;
int p;
if(n<=0)
return 0;
if(n==1)
{
if(rec+s2[hr]<ans)
{
ans=rec+s2[hr];
pos=s2[hr];
}
else if(rec+s2[hr]==ans)
{
if(pos>s2[hr])
pos=s2[hr];
}
return 0;
}
rec+=s2[hr];
for(int i=zl; i<=zr; i++)
{
if(s2[hr]==s1[i])
p=i;
}
Build(s1,s2,zl,p-1,hl,hl+p-zl-1);
Build(s1,s2,p+1,zr,hr-(zr-p),hr-1);
rec-=s2[hr];
}
int main()
{
int s1[maxn];
int s2[maxn];
char s;
while(scanf("%d%c",&s1[ii++],&s)!=EOF)
{
ans=maxn;
if(s!='\n')
{
while(scanf("%d%c",&s1[ii++],&s))
{
if(s=='\n')
break;
}
}
for(int i=0; i<ii; i++)
scanf("%d",&s2[i]);
Build(s1,s2,0,ii-1,0,ii-1);
printf("%d\n",pos);
ii=0;
ans=maxn;
pos=-1;
rec=0;
}
}