题意:输入中序和后序,求从根结点到叶子结点路径上的和最小的叶子结点的值
分析:可先由中序和后序建树,后序可确定根,中序可确定左右子树,依次类推,递归思想
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stu
{
int c;
struct stu *l,*r;
}Tree;
int min,l;
void creat(Tree **T,int *z,int m1,int n1,int *h,int m2,int n2)
{
int i;
*T=NULL;
if(m1==n1){
*T=(Tree *)malloc(sizeof(Tree));
(*T)->c=z[m1];
(*T)->l=(*T)->r=NULL;
}
else{
for(i=m1;i<=n1;i++)
if(z[i]==h[n2])
break;
*T=(Tree *)malloc(sizeof(Tree));
(*T)->c=h[n2];
if(i-1>=m1&&i+1<=n1){
creat(&(*T)->l,z,m1,i-1,h,m2,m2+i-m1-1);
creat(&(*T)->r,z,i+1,n1,h,m2+i-m1,n2-1);
}
else if(i-1<m1&&i+1<=n1){
creat(&(*T)->r,z,i+1,n1,h,m2+i-m1,n2-1);
(*T)->l=NULL;
}
else if(i-1>=m1&&i+1>n1){
creat(&(*T)->l,z,m1,i-1,h,m2,m2+i-m1-1);
(*T)->r=NULL;
}
}
}
int dfs(Tree *T,int m)
{
int sum;
m+=T->c;
if(T->l==NULL&&T->r==NULL){
if(m<min){
min=m;
l=T->c;
}
return 0;
}
sum=T->c;
if(T->l==NULL&&T->r)
sum+=dfs(T->r,m);
else if(T->r==NULL&&T->l)
sum+=dfs(T->l,m);
else if(T->l&&T->r){
sum+=dfs(T->l,m);
sum+=dfs(T->r,m);
}
return sum;
}
int main()
{
int z[10010],h[10010],i,n1,n2;
char c;
Tree *T=NULL;
while(scanf("%d",&z[1])!=EOF){
c=getchar();
for(i=2;c!='\n';i++){
scanf("%d",&z[i]);
c=getchar();
}
n1=i-1;
scanf("%d",&h[1]);
c=getchar();
for(i=2;c!='\n';i++){
scanf("%d",&h[i]);
c=getchar();
}
n2=i-1;
creat(&T,z,1,n1,h,1,n2);
min=200000000;
dfs(T,0);
printf("%d\n",l);
}
return 0;
}