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.
给出中序遍历和后序遍历,让你建一颗树,也就是让你求前序遍历,个人认为建树其实是这题最困难的,怎么建树?是很多数据结构题都比较头疼的部分,这道题的建树方法就是开两个数组,每个结点都有两个儿子结点,如果没有儿子结点就为0;然后就是遍历这棵树了;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=4001000;
const LL mod=998244353;
int a1[10100],a2[10100];
int lch[10100],rch[10100];
int mmin,best;
int build(int l,int r,int p){
if(l>r) return 0;
int ans=0,s=0;
for(int i=l;i<=r;i++){
if(a1[i]==a2[p]){
ans=i;
break;
}
s++;
}
int root=a1[ans];
lch[root]=build(l,ans-1,p-r+l+s-1);
rch[root]=build(ans+1,r,p-1);
return root;
}
void dfs(int p,int s){
s+=p;
if(lch[p]==0&&rch[p]==0){
if(s<mmin){
best=p;
mmin=s;
}
else if(s==mmin) best=min(best,p);
}
if(lch[p]) dfs(lch[p],s);
if(rch[p]) dfs(rch[p],s);
}
int main(){
ios::sync_with_stdio(false);
string s1,s2;
while(getline(cin,s1)){
stringstream ss1(s1);
getline(cin,s2);
stringstream ss2(s2);
int i1=0,i2=0,x;
while(ss1>>x) a1[++i1]=x;
while(ss2>>x) a2[++i2]=x;
int rt=build(1,i1,i1);
mmin=2e9,best=2e9;
dfs(rt,0);
cout<<best<<endl;
}
return 0;
}