UVA-548 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

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 // oj.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <numeric>

using namespace std;

int I[10010];
int P[10010];

int ans;
int minp;

void solve(int beg, int end, int left, int path)
{
if (beg == end)
return;
if (end - beg <= 1)
{
if (I[beg] + path < minp)
{
minp = I[beg] + path;
ans = I[beg];
}
return;
}
int i = find(I + beg, I + end, P[left]) - I;
solve(i + 1, end, left - 1, path + P[left]);
solve(beg, i, left - end + i, path + P[left]);
}

int main()
{
ios::sync_with_stdio(false);
string L, M;
while (getline(cin, L))
{
getline(cin, M);
minp = numeric_limits<int>::max();
istringstream stL(L), stM(M);
int N = 0;
while (stL >> I[N])
stM >> P[N++];
solve(0, N, N - 1, 0);
cout << ans << endl;
}
return 0;
}

解析&吐槽:

通过中序和后序遍历重建二叉树。需要注意的是题目要求输出“最短的一条路径” 的叶子节点的值。也就是说需要把分支节点的值也考虑在内。

本作品采用 署名-相同方式共享 4.0 国际 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 “不科学的科学君” (Liu233w) 与博客链接: https://liu233w.github.io ,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

加载评论框需要翻墙