zoukankan      html  css  js  c++  java
  • 给出二叉树的中后序遍历 建立二叉树 并找出权和最小值

    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 << "
    ";
    62     }
    63     return 0;
    64 }
    65         
  • 相关阅读:
    HDU 1058 Humble Numbers
    HDU 1421 搬寝室
    HDU 1176 免费馅饼
    七种排序算法的实现和总结
    算法纲要
    UVa401 回文词
    UVa 10361 Automatic Poetry
    UVa 537 Artificial Intelligence?
    UVa 409 Excuses, Excuses!
    UVa 10878 Decode the tape
  • 原文地址:https://www.cnblogs.com/ZZZZone/p/6041690.html
Copyright © 2011-2022 走看看