问题连接:https://odzkskevi.qnssl.com/630fcbec9466ed05dd8215b60e322fde?v=1535019630
题意:
这个题是给你先序和后序遍历,让你去找从根节点到叶子节点之和的最小路径,然后把这个路径的叶子节点输出出来,如果有多个把叶子节点最小的输出出来。
思路:
这个题是多组输入,还没有数据结束条件所以还要当成字符串去处理,然后就是通过先序和后序顺序建树,然后遍历去寻找符合条件的结果。
代码:
#define N 10010
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[N],b[N];
int n,mi,ad;
struct node
{
int rt;
node *l,*r;
};
node *shu(int x,int y,int z)//x是先序遍历的子树起点,y是后序的子树起点(即使当前子树的根节点),
{
if(z<=0)return NULL;
node *p=(node*)malloc(sizeof(node));
p->rt=b[y];
int dis;
for(int i=x; i>=0; i--)//寻找先序中的子树根节点
{
if(a[i]==b[y])
{
dis=i;
break;
}
}
int t=x-dis;
p->r=shu(x,y-1,t);//右子树
p->l=shu(dis-1,y-t-1,z-t-1);//左子树
return p;
}
int dfs(node *p,int sum)
{
if(p!=NULL)
{
int x=dfs(p->l,sum+p->rt);
int y=dfs(p->r,sum+p->rt);
if(x&&y)//当前位置是树叶
{
if(sum+p->rt<mi)//计算节点和
{
mi=sum+p->rt;
ad=p->rt;
}
else if(sum+p->rt==mi)
ad=min(ad,p->rt);
}
return 0;
}
else return 1;
}
int main()
{
char c[20*N];
while(gets(c))
{
int add=0;n=0;
for(int i=0; i<strlen(c); i++)//处理先序遍历的数据
{
if(c[i]==' ')
{
a[n++]=add;add=0;
}
else add=add*10+c[i]-'0';
}
a[n++]=add;
for(int i=0; i<n; i++)//后序遍历
scanf("%d",&b[i]);
getchar();
mi=0x3f3f3f3f;
node *root=(node*)malloc(sizeof(node));
root=shu(n-1,n-1,n);//建树
dfs(root,0);
printf("%d\n",ad);
}
return 0;
}