您的位置:首页 > 其它

UVa 548 Tree (中序遍历&后序遍历&DFS)

2013-10-28 15:08 417 查看

548 - Tree

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=489

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: