548 - Tree
Time limit: 3.000 seconds
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
把建树和DFS两步合并,详见代码。
完整代码:
/*0.086s*/
#include<cstdio>
#include<algorithm>
using namespace std;
int in[10010], post[10010], min_sum, ans;
void dfs(int n, int* in, int* post, int sum)
{
if (n <= 0) return;
int p = find(in, in + n, post[n - 1]) - in;
sum += post[n - 1];
if (n == 1)
{
if (sum < min_sum)
{
min_sum = sum;
ans = post[n - 1];
}
///you should output the value of the leaf node of a path of least value.
else if (sum == min_sum)
ans = min(ans, post[n - 1]);
///In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
return;
}
dfs(p, in, post, sum);///左子树
dfs(n - p - 1, in + p + 1, post + p, sum);///右子树
}
int main()
{
char ch;
int n, i;
while (~scanf("%d%c", &in[0], &ch))
{
if (ch == 10)///只读了一个数(就换行了)
{
scanf("%d", &post[0]);
printf("%d\n", post[0]);
continue;
}
n = 1;
while (scanf("%d%c", &in[n++], &ch), ch != 10)
;
for (i = 0; i < n; ++i)
scanf("%d", &post[i]);
ans = min_sum = -1u >> 1;
dfs(n, in, post, 0);
printf("%d\n", ans);
}
return 0;
}

本文探讨了如何确定给定二叉树中路径最小值对应的叶节点值,通过输入二叉树的中序和后序遍历序列,采用深度优先搜索策略优化求解过程,最终输出路径最短的叶节点值。
638

被折叠的 条评论
为什么被折叠?



