uvaTree(二叉树)

题目链接:

lrj--p155。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<string>
 5 #include<sstream>
 6 using namespace std;
 7 const int maxn=10010;
 8 int post[maxn],med[maxn],lson[maxn],rson[maxn];
 9 int best,best_sum;
10 
11 int build(int l1,int r1,int l2,int r2 )
12 {
13     if(l1>r1) return 0;
14     int root=post[r2];
15     int p=l1;
16     while(med[p]!=root) p++;
17     int cnt=p-l1;  //左子树
18     lson[root]=build(l1,p-1,l2,l2+cnt-1);
19     rson[root]=build(p+1,r1,l2+cnt,r2-1);
20     return root;
21 }
22 void dfs(int u,int sum)
23 {
24     sum+=u;
25     if(!lson[u]&&!rson[u]) {
26         if(sum<best_sum||sum==best_sum&&u<best) {best=u;best_sum=sum;}
27 
28     }
29 
30     if(lson[u]) dfs(lson[u],sum);
31     if(rson[u]) dfs(rson[u],sum);
32 }
33 string s1;
34 int main()
35 {
36     while(getline(cin,s1))
37     {
38         int v;
39         stringstream ss(s1);
40         int c=0;
41         while(ss>>v) med[c++]=v;
42         int len=c;
43         for(int i=0;i<len;i++)
44             cin>>post[i];
45         build(0,len-1,0,len-1);
46         best_sum=100000000;
47         dfs(post[len-1],0);
48         cout<<best<<"\n";
49         getchar();
50 
51 
52     }
53     return 0;
54 }

 

posted @ 2017-03-24 19:35  yijiull  阅读(79)  评论(0编辑  收藏  举报