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<algorithm>
using namespace std;
int in[10010];
int post[10010];
int mSum;
int res;
int find(int key, int*array, int n)
{
int i;
for (i=0; i<n; i++)
{
if (array[i]==key)
return i;
}
return -1;
}
void dfs(int n, int*in, int*post, int sum)
{
if (n<=0)
return;
int root=post[n - 1];
if (n==1)
{
int tmpSum=sum +root;
if (tmpSum<mSum)
{
mSum=tmpSum;
res=root;
}
else if (tmpSum==mSum)
res=res<root ? res : root;
return;
}
int index=find(post[n - 1], in, n);
dfs(index, in, post, sum + root);
dfs(n-index-1, in+index+1, post+index, sum+root);
}
int main()
{
char ch;
int i,n;
while (~scanf("%d%c",&in[0],&ch))
{
mSum=0x7fffffff;
res=0x7fffffff;
if (ch=='\n')
{
scanf("%d", &post[0]);
printf("%d\n", post[0]);
continue;
}
n=1;
while (scanf("%d%c",&in[n++],&ch))
{
if (ch=='\n')
break;
}
for (i=0; i<n; i++)
scanf("%d", &post[i]);
dfs(n, in, post, 0);
printf("%d\n", res);
}
return 0;
}