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
题目意思:给出树的中序遍历和后序遍历,让输出树中从根到叶子节点路径和最小的叶子节点的值:
解题思路:由中序和后序,可以建好一棵树,然后遍历得到所有路径的和和叶子节点的值,然后找到最小的就可以了。
#include <iostream>
#include<deque>
#include<algorithm>
#include<cstdio>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<sstream>
#include<cctype>
#include<queue>
#include<cstdlib>
#include<cstring>
using namespace std;
struct node
{
int data;
node*left,*right;
node(int a):data(a),left(0),right(0) {}
};
node* insert(node*root,int v,int value[])
{
if(root==NULL)
{
return new node(v);
}
else if(value[v]<value[root->data])
{
node*t=insert(root->left,v,value);
if(root->left==NULL)
root->left=t;
}
else
{
node*t=insert(root->right,v,value);
if(root->right==NULL)
root->right=t;
}
}
void get_min(node*root,int sum,vector<pair<int,int> >&v)
{
if(root)
{
if(root->left==NULL&&root->right==NULL)
{
//cout<<sum+root->data<<"*"<<root->data<<endl;
v.push_back(make_pair(sum+root->data,root->data));
}
get_min(root->left,sum+root->data,v);
get_min(root->right,sum+root->data,v);
}
}
int main()
{
string line;
int value[10001];
int num;
vector<pair<int,int> >v;
vector<int>v1;
vector<int>v2;
while(getline(cin,line))
{
istringstream in1(line);
v.clear(),v1.clear(),v2.clear();
while(in1>>num)v1.push_back(num);
getline(cin,line);
istringstream in2(line);
while(in2>>num)v2.push_back(num);
for(int i=0; i<(int)v1.size(); i++)
value[v1[i]]=i;
node*root=new node(v2[v2.size()-1]);
for(int i=v2.size()-2; i>=0; i--)
{
insert(root,v2[i],value);
}
get_min(root,0,v);
int min_dis=2100000000,min;
for(int i=0; i<v.size(); i++)
if(min_dis>v[i].first)
{
min_dis=v[i].first;
min=v[i].second;
}
cout<<min<<endl;
}
return 0;
}