首页 > 代码库 > uva 548 - Tree

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

 

Sample Output 

 

13255
#include <iostream>#include <stack>#include <cstring>#include <cstdio>#include <string>#include <algorithm>#include <queue>#include <set>#include <map>#include <fstream>#include <stack>#include <list>#include <sstream>/*中序:左中右后序:左右中由后序的特点可得后序的最后一个必定是树的根,在根据根结点在中序的位置,位置左边则是左子树,右边则是右子树。依次递归例如:3 2 1 4 5 7 63 1 2 5 6 7 4根为4;3 2 1 为左子树,5 7 6为右子树。3 2 1    5 7 63 1 2  5 6 7另外可以观察到每生成一个右子树,该右子树的根在后序中的位置会向左偏移一个位置,也就说右子树套右子树向左的偏移值则为2,例如   5 7 65 6 7偏移值为1根为7  5左子树,6右子树 5              65 偏移值为1  6  偏移值为2*/using namespace std;#define ms(arr, val) memset(arr, val, sizeof(arr))#define N 10005#define INF 0x3fffffff#define vint vector<int>#define setint set<int>#define mint map<int, int>#define lint list<int>#define sch stack<char>#define qch queue<char>#define sint stack<int>#define qint queue<int>int in[N], post[N];int in_n, layer, sum, _max, ans;/*layer右子树的偏移程度*/void buildtree(int i, int j){    if (i > j)    {        return;    }    int val = post[j - layer];    sum += val;    if (i == j)    {        if (sum < _max || (sum == _max && val < ans))        {            _max = sum;            ans = val;        }    }    else    {        buildtree(i, in[val] - 1);        layer++;//进入右子树,偏移值+1        buildtree(in[val] + 1, j);        layer--;//退出则-1    }    sum -= val;}int main(){    int t;    while (~scanf("%d", &t))    {        in_n = layer = sum = 0;        _max = INF;        while (true)        {            in[t] = in_n++;            if (getchar() == \n)            {                break;            }            scanf("%d", &t);        }        for (int i = 0; i < in_n; i++)        {            scanf("%d", &post[i]);        }        buildtree(0, in_n - 1);        cout<<ans<<endl;    }        return 0;}