UVa 548 - Tree

来源:互联网 发布:网上真钱炸金花软件 编辑:程序博客网 时间:2024/06/06 20:13

 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 63 1 2 5 6 7 47 8 11 3 5 16 12 188 3 11 7 16 18 12 5255255

Sample Output 

13255



Miguel A. Revilla 
1999-01-11


#include <iostream>#include <cstring>#include <string>#include <cstdlib>#include <cstdio>using namespace std;const int MAX = 1000000+5;int in[MAX], aft[MAX];int ans=1e9;long long sum=0, min_sum=1e9;bool l,r;bool preOrder(int *in, int *aft, int length, int sum){if(length==0)return true;sum += *(aft+length-1);int index=0;for(; index < length; index++){if(in[index]==*(aft+length-1))break;}l = preOrder(in, aft, index, sum);// 无左树// 无右树r = preOrder(in+index+1, aft+index, length-index-1, sum);if(l&&r){if(sum < min_sum){min_sum = sum;ans =*(aft+length-1);}else if(sum==min_sum)ans = min(ans, *(aft+length-1));}return false;}int min(int a, int b){return a<b?a:b;}int convertData(char *s, int *v){int top=0;    for(int i=0;s[i];i++)    {        while(s[i]==' ')        i++;        v[top]=0;        while(s[i]&&isdigit(s[i]))        {            v[top]=v[top]*10+s[i]-'0';            i++;        }        top++;        if(!s[i]) break;    }    return top;}void init(){ sum=0; ans = 1e9; min_sum=1e9;}int main(){//freopen("in.txt","r",stdin);char ch[MAX];while(cin.getline(ch, sizeof(ch))){init();int length = convertData(ch, in);cin.getline(ch, sizeof(ch));convertData(ch, aft);preOrder(in, aft, length, 0);cout << ans << endl;}return 0;}


1 0
原创粉丝点击