You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
Sample Input
3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255
Sample Output
1 3 255
思路:先通过中序遍历和后序遍历构造二叉树,之后再去找权值最小的树叶。
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
int u;
node *l,*r;
};
int a[10010],b[10010],minn,flag;
node *shu(int x,int y,int z)
{
if(z<=0)
return NULL;
node *p=(node*)malloc(sizeof(node));
p->u=b[y];
int k;
for(int i=x; i>=0; i--)
{
if(a[i]==b[y])
{
k=i;
break;
}
}
int t=x-k;
p->r=shu(x,y-1,t);
p->l=shu(k-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->u);
int y=dfs(p->r,sum+p->u);
if(x&&y)
{
if(sum+p->u<minn)
{
minn=sum+p->u;
flag=p->u;
}
else if(sum+p->u==minn)
{
if(flag>p->u)
flag=p->u;
}
}
return 0;
}
else
return 1;
}
int main()
{
char s[200000];
while(gets(s))
{
int x=0,k=0;
for(int i=0; i<strlen(s); i++)
{
if(s[i]==' ')
{
a[k++]=x;
x=0;
}
else
x=x*10+s[i]-'0';
}
a[k++]=x;
for(int i=0; i<k; i++)
scanf("%d",&b[i]);
getchar();
node *tree=(node*)malloc(sizeof(node));
tree=shu(k-1,k-1,k);
minn=0x3f3f3f3f;
dfs(tree,0);
printf("%d\n",flag);
}
return 0;
}