您的位置:首页 > 其它

UVa 548 - Tree

2013-03-03 15:22 344 查看
Tree
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


Miguel A. Revilla

1999-01-11

 

 

#include <stdio.h>
int min,leaf;
void build(int *in,int *post,int i,int j,int sum)
{
int k;
int *p=in;
for(k=0;k<i;k++,p++)
if(*post==*p)break;
sum+=*post;
if(k==0&&i==1)
{
if(sum<min)
{
leaf=(*in);
min=sum;
}
else if(sum==min&&leaf>=*in)leaf=*in;
return;
}
if(i-k-1)build(in+k+1,post-1,i-k-1,i-1-k,sum);
if(k)build(in,post-i+k,k,k,sum);
}
int main()
{
int i=0,j=0,in[10005],post[10005];
char c;
while((scanf("%d%c",&in[i++],&c))!=EOF)
{
min=100000;
if(c!='\n')while(((scanf("%d%c",&in[i++],&c))!=EOF)&&c!='\n');
while(((scanf("%d%c",&post[j++],&c))!=EOF)&&c!='\n');
build(&in[0],&post[j-1],i,j,0);
printf("%d\n",leaf);
i=0;j=0;
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树