题目:
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#define maxn 11111
char s1[maxn], s2[maxn];
int in[maxn], post[maxn];
const int INF =0x3f3f3f3f;
struct node
{
int data;
node* left;
node* right;
};
node* build(int* in, int* post, int il, int ih, int pl, int ph)
{
if(il>ih)
{
return NULL;
}
node* root=(node*)malloc(sizeof(node));
root->data=post[ph];
int rootInd=il;
while(in[rootInd]!=root->data) rootInd++;
int llen=rootInd-il;
int rlen=ih-rootInd;
root->left=build(in,post,il,il+llen-1,pl,pl+llen-1);
root->right=build(in,post,rootInd+1,ih,pl+llen,ph-1);
return root;
}
int getNum(char s[], int len, int a[])
{
int num=0;
int ind=0;
for(int i=0;i<len;i++)
{
if(s[i]==' ')
{
a[ind++]=num;
num=0;
}
else
{
num=num*10+s[i]-'0';
}
}
a[ind]=num;
ind++;
return ind-1;
}
int minPath=INF;
int minnode;
void dfs(node* u, int sum)
{
if(u!=NULL)
{
if(u->right==NULL&&u->left==NULL)
{
if(sum+u->data<minPath||(sum+u->data==minPath&&u->data<minnode))
{
minPath=sum+u->data;
minnode=u->data;
}
}
dfs(u->left,sum+u->data);
dfs(u->right,sum+u->data);
}
}
int main()
{
int numcnt;
while(gets(s1)&&gets(s2))
{
getNum(s1,strlen(s1),in);
numcnt=getNum(s2,strlen(s2),post);
node* root=build(in,post,0,numcnt,0,numcnt);
minPath=INF;
minnode=root->data;
dfs(root,0);
printf("%d\n",minnode);
}
return 0;
}
|