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<cstdio>
#include<cstring>
#include<malloc.h>
int w,minn,flag;
int zh[100100],ho[100100];
char s[100100];
struct node
{
int v;
node *lch,*rch;
};
node *insert(int x,int y,int l)
{
if(l<=0)
return NULL; //空
node *root=(node*)malloc(sizeof(node));
root->v=ho[x];
int p;
for(int i=y; i>=0; i--)
if(zh[i]==ho[x]) //在中序遍历中找到数值一样的数的位置
{
p=i;
break;
}
int k=y-p;
root->rch=insert(x-1,y,k);
root->lch=insert(x-k-1,p-1,l-k-1);
return root;
}
int dfs(node *root,int sum)
{
if(root!=NULL)
{
int x=dfs(root->lch,sum+root->v);
int y=dfs(root->rch,sum+root->v);
if(x&&y)
{
if(sum+root->v<minn)
{
minn=sum+root->v;
flag=root->v;
}
else if(sum+root->v==minn) //长度一样,取叶节点小的值
flag=root->v<flag?root->v:flag;
}
return 0;
}
else
return 1;
}
int main()
{
while(gets(s))
{
int l=strlen(s);
int a=0,b=0;
for(int i=0; i<l; i++)
{
if(s[i]==' ')
{
zh[b++]=a;
a=0;
}
else
a=a*10+s[i]-'0';
}
zh[b++]=a;
for(int i=0; i<b; i++)
scanf("%d",&ho[i]);
getchar();
w=b;
node *root=(node*)malloc(sizeof(node));
root=insert(b-1,b-1,b);
minn=0x3f3f3f3f;
int x=dfs(root,0);
printf("%d\n",flag);
}
return 0;
}