首页 > 代码库 > Tree

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



Miguel A. Revilla
1999-01-11

题意:给出一颗树的中序遍历和后序遍历;然后要你求出从根节点到叶节点所经过的结点的最小值的叶节点;若果值相等,那么输出较小的那个。

<span style="font-size:14px;"># include <cstdio>
# include <string>
# include <sstream>
# include <algorithm>
# include <iostream>
using namespace std;

int in_order[10005],out_order[10005],n,lch[10005],rch[10005],best,best_sum;

bool read_list(int *a)      // 读入字符串;
{
	string s;
	if(!getline(cin,s))    return false;   //如果为空,那么返回假,跳出循环;
	stringstream ss(s);
	n=0;
	while(ss>>a[n])   n++;     //使用流,将数据读入数组;
	return n>0;      //返回n的值;
}

int build(int l1,int r1,int l2,int r2)      //建立树;查找根结点;后序遍历的最后一个肯定是根结点;然后
{                                           //根据根结点的位置,分出根结点的左分枝和右分枝;
	if(l1>r1)    return 0;
	int root=out_order[r2],p=l1;
	while(in_order[p]!=root)    p++;
	int cnt=p-l1;
        lch[root]=build(l1,p-1,l2,l2+cnt-1);
	rch[root]=build(p+1,r1,l2+cnt,r2-1);
	return root;
}

int dfs(int root,int sum)       //从根节点开始遍历,找出和最小的叶节点;
{
	sum+=root;
	if(!lch[root]&&!rch[root])   //判断是否到叶节点;
	{
		if(sum<best_sum||(sum==best_sum&&root<best))
		{
			best_sum=sum;   best=root;
		}
	}
	if(lch[root])    dfs(lch[root],sum);
	if(rch[root])    dfs(rch[root],sum);
	return 0;
}

int main()
{
	//freopen("a.txt","r",stdin);
	while(read_list(in_order))
	{
		read_list(out_order);
		build(0,n-1,0,n-1);
		best_sum=1000000;       //赋初始值;
		dfs(out_order[n-1],0);
		cout<< best <<'\n';
	}
	return 0;
}</span>


Tree