题目:
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<string.h>
#include<malloc.h>
char s[100861];
int inorder[10086],postorder[10086],min,nmin;
typedef struct Tnode
{
int date;
struct Tnode *right,*left;
}node;
node *newnode()
{
int i;
node *p;
p=(node *)malloc(sizeof(node));
p->left=NULL;
p->right=NULL;
return p;
}
void bulid(int L,int *p,int *q,node *subtree,int sum)
{
int i,v;
subtree=newnode();
if(L==1)
{
if(p[0]+sum<min)
{
min=sum+p[0];
nmin=p[0];
}
return ;
}
v=q[L-1];
subtree->date=v;
for(i=0;i<L;i++)
if(p[i]==q[L-1])
break;
if(i>=1)
bulid(i,p,q,subtree->left,sum+v);
if(L-i-1>=1)
bulid(L-i-1,p+i+1,q+i,subtree->right,sum+v);
}
int change(char *p,int *d)
{
int i,j,k=0;
for(i=0;i<strlen(p);)
{
if(p[i]>='0'&&p[i]<='9')
{
j=0;
while(p[i]>='0'&&p[i]<='9')
{
j=j*10+p[i]-'0';
i++;
}
d[k++]=j;
}
else i++;
}
return k;
}
int main()
{
int i,L,sum;
node *root;
while(gets(s))
{
change(s,inorder);
gets(s);
L=change(s,postorder);
min=0x3f3f3f3f;
sum=0;
bulid(L,inorder,postorder,root,sum);
printf("%d\n",nmin);
}
return 0;
}