danielvitor23

1195 - Árvore Binária de Busca

Nov 6th, 2021
1,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int MAX = 550;
  5.  
  6. struct node {
  7.   int val;
  8.   int esq, dir;
  9.   node () {
  10.     esq = -1;
  11.     dir = -1;
  12.   }
  13. };
  14.  
  15. int n, a[MAX];
  16. vector<node> st;
  17.  
  18. void insert(int no, int val) {
  19.   if (val < st[no].val) {
  20.     if (st[no].esq == -1) {
  21.       st.push_back(node());
  22.       st[no].esq = st.size()-1;
  23.       st[st[no].esq].val = val;
  24.     } else {
  25.       insert(st[no].esq, val);
  26.     }
  27.   } else {
  28.     if (st[no].dir == -1) {
  29.       st.push_back(node());
  30.       st[no].dir = st.size()-1;
  31.       st[st[no].dir].val = val;
  32.     } else {
  33.       insert(st[no].dir, val);
  34.     }
  35.   }
  36. }
  37.  
  38. void pre(int no) {
  39.   cout << ' ' << st[no].val;
  40.   if (st[no].esq != -1) pre(st[no].esq);
  41.   if (st[no].dir != -1) pre(st[no].dir);
  42. }
  43.  
  44. void in(int no) {
  45.   if (st[no].esq != -1) in(st[no].esq);
  46.   cout << ' ' << st[no].val;
  47.   if (st[no].dir != -1) in(st[no].dir);
  48. }
  49.  
  50. void post(int no) {
  51.   if (st[no].esq != -1) post(st[no].esq);
  52.   if (st[no].dir != -1) post(st[no].dir);
  53.   cout << ' ' << st[no].val;
  54. }
  55.  
  56. int main() {
  57.   cin.tie(0)->sync_with_stdio(0);
  58.   int tc; cin >> tc;
  59.   int C = 1;
  60.   while (tc--) {
  61.     cout << "Case " << C++ << ":\n";
  62.     cin >> n;
  63.     for (int i = 0; i < n; ++i) {
  64.       cin >> a[i];
  65.     }
  66.  
  67.     st.clear();
  68.     st.push_back(node());
  69.     st.back().val = a[0];
  70.    
  71.     for (int i = 1; i < n; ++i) {
  72.       insert(0, a[i]);
  73.     }
  74.  
  75.     cout << "Pre.:";
  76.     pre(0);
  77.     cout << '\n';
  78.     cout << "In..:";
  79.     in(0);
  80.     cout << '\n';
  81.     cout << "Post:";
  82.     post(0);
  83.     cout << '\n';
  84.     cout << '\n';
  85.   }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment