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 <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <string.h>
#define inf 0x3fffffff
using namespace std;
int pos[10010],in[10010];
int local;
int mins=inf;
struct node
{
int x;
struct node *lchil;
struct node *rchil;
};
/*node *newnode(int x)
{
node *Node=new node;
Node->lchil=NULL;
Node->rchil=NULL;
return Node;
}*/
/*void searchs(node *root,int newdata,int a)
{
if(root==NULL){
return ;
}
if(root->x==a){
root->x=newdata;
}
searchs(root->lchil,newdata,a);
searchs(root->rchil,newdata,a);
}*/
/*void inserts(node* &root,int x)
{
if(root==NULL){
root=newnode(x);
return ;
}
if
}*/
node *create(int posl,int posr,int inl,int inr)
{
if(posl>posr){ return NULL;}
node*root=new node;
root->x=pos[posr];
int k;
for(k=inl;k<=inr;k++){
if(in[k]==pos[posr]){break;}
}
int numleft=k-inl;
root->lchil=create(posl,posl+numleft-1,inl,k-1);
root->rchil=create(posl+numleft,posr-1,k+1,inr);
return root;
}
int dfs(node*root,int sum)
{
sum+=root->x;
if(root->lchil==NULL&&root->rchil==NULL){
if(sum<mins){
mins=sum;
local=root->x;
}
return root->x;
}
if(root->lchil==NULL&&root->rchil!=NULL) dfs(root->rchil,sum);
else if(root->lchil!=NULL&&root->rchil==NULL) dfs(root->lchil,sum);
else {
dfs(root->lchil,sum);
dfs(root->rchil,sum);
}
return 0;
}
int main()
{
node *root;
while(scanf("%d",&in[1])!=EOF){
mins=inf;
local=-1;
int k1=2;
while(1){
char c=getchar();
if(c=='\n') break;
scanf("%d",&in[k1++]);
}
k1--;
int k2=1;
while(1){
scanf("%d",&pos[k2++]);
char c=getchar();
if(c=='\n') break;
}
k2--;
root=create(1,k1,1,k2);
dfs(root,0);
printf("%d\n",local);
}
return 0;
}