给出二叉树的中后序遍历 建立二叉树 并找出权和最小值

 

Dfs类型题

收获:明确二叉树的三种优先遍历,以及用c++输入流输出流的使用

 

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cstdlib>
 6 #include<sstream>
 7 #include<iostream>
 8 
 9 using namespace std;
10 const int MaxN = 1e4;
11 int in_order[MaxN + 5], post_order[MaxN + 5];
12 int lch[MaxN+ 5], rch[MaxN + 5];
13 int n;
14 int best, best_sum = 1<<30;
15 
16 bool read_list(int *a)
17 {
18     string line;
19     if(!getline(cin, line)) return false;
20     stringstream ss(line);
21     n = 0;
22     int x;
23     while(ss >> x) a[n++] = x;
24     return n > 0;
25 }
26 
27 int Build(int L1, int R1, int L2, int R2)
28 {
29     if(L1 > R1)return 0;
30     int root = post_order[R2];
31     int p = L1;
32     while(in_order[p] != root) p++;
33     int cnt = p - L1;
34     lch[root] = Build(L1, p - 1, L2, L2 + cnt - 1);
35     rch[root] = Build(p + 1, R1, L2 + cnt, R2 - 1);
36     return root;
37 }
38 void Dfs(int u, int sum)
39 {
40     sum = sum + u;
41     if(!lch[u] && !rch[u])
42     {
43         if(sum < best_sum || (sum == best_sum && u < best))
44         {
45             best = u;
46             best_sum = sum;
47         }
48     }
49     if(lch[u]) Dfs(lch[u], sum);
50     if(rch[u]) Dfs(rch[u], sum);
51 }
52 
53 int main()
54 {
55     while(read_list(in_order))
56     {
57         best_sum = 1<<30;
58         read_list(post_order);
59         Build(0, n - 1, 0, n - 1);
60         Dfs(post_order[n - 1], 0);
61         cout << best << "\n";
62     }
63     return 0;
64 }
65         

 

posted @ 2016-11-08 10:03  ZZZZone  阅读(515)  评论(0编辑  收藏  举报