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
题意:
给出中序和后序遍历,求叶节点到根的和最小的叶节点的值。
首先是输入格式,用line和count处理。
然后是建树,用递归的方式建树,可以当做模版。然后递归求解即可。
代码:
#include<iostream>
#include<cstdio>
#include<climits>
using namespace std;
const int maxn=10005;
int in[maxn],post[maxn];
int count,line,minn=INT_MAX,ans;
struct node{
int data;
node*l,*r;
};
void build(int n,int in[],int post[],node **root){ //建树
if(n<=0) return ;
int i,num;
*root=new node;
(*root)->data=post[n-1]; //后序的最有一个一定是根节点
(*root)->l=NULL;
(*root)->r=NULL;
i=0;
num=post[n-1];
for(i=0;i<n;++i){ //找到根节点在中序中位置
if(in[i]==num)
break;
}
build(i,in,post,&(*root)->l); //递归建立中序左边i个节点
build(n-i-1,in+i+1,post+i,&(*root)->r); //递归建立中序右边n-i-1个节点
}
void find_least_node(int val,node *root){
if(root){
val+=root->data;
if(!(root->l)&&!(root->r)){
if(val<minn){
minn=val;
ans=root->data;
}
}
else{
if(root->l)
find_least_node(val,root->l);
if(root->r)
find_least_node(val,root->r);
}
}
}
void remove(node *root){
if(root){
if(root->l)
remove(root->l);
if(root->r)
remove(root->r);
delete root;
}
}
int main()
{
int num;
char ch;
node * root=NULL;
while(~scanf("%d%c",&num,&ch)){
if(line==0)
in[count++]=num;
else if(line==1) post[count++]=num;
if(ch=='\n'){
line++;
if(line==2){
root=NULL;
build(count,in,post,&root);
find_least_node(0,root);
remove(root);
printf("%d\n",ans);
minn=INT_MAX;
count=0;
line=0;
}
count=0;
}
}
return 0;
}