Advertisement
tungSfer

balanced_BST

May 24th, 2021
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define ll long long
  4. #define el endl
  5. #define umi unordered_map<int, int>
  6. #define umll unordered_map<ll, ll>
  7. #define all(vect) vect.begin(), vect.end()
  8. #define reset(A) memset(A, 0, sizeof(A))
  9.  
  10. const int mod = 1e9 + 7;
  11.  
  12. using namespace std;
  13.  
  14. struct node
  15. {
  16.     int val;
  17.     node *l, *r;
  18. };
  19.  
  20. node *create(int x)
  21. {
  22.     node *p = new node;
  23.     p->val = x;
  24.     p->l = NULL;
  25.     p->r = NULL;
  26.     return p;
  27. }
  28.  
  29. node * insert(node * root, int x){
  30.     node *p = root;
  31.     if(p == NULL)
  32.     {
  33.         node * temp = create(x);
  34.         return temp;
  35.     }
  36.     else
  37.     {
  38.         if(x < p -> val)
  39.             p -> l = insert(p -> l, x);
  40.         else
  41.             p -> r = insert(p -> r, x);
  42.     }
  43.     return p;
  44. }
  45.  
  46. int pre(node *root)
  47. {
  48.     int res = 0;
  49.     node *p = root;
  50.     if(p->l == NULL && p->r == NULL)
  51.         res++;
  52.     cout <<  p->val << " ";
  53.     if(p->l != NULL)
  54.     {
  55.         res += pre(p->l);
  56.     }  
  57.     if(p->r != NULL)
  58.     {
  59.         res += pre(p->r);
  60.     }
  61.     return res;
  62. }
  63.  
  64. node *build(node *root, int a[], int st, int en)
  65. {
  66.     if(st > en)
  67.         return;
  68.     node *p = root;
  69.     int r = (en - st) / 2;
  70.     if(p->l == NULL && p->r == NULL)
  71.         p = insert(p, a[r]);
  72.     p->l = (p, a, st, r - 1);
  73.     p->r = (p, a, r + 1, en);
  74. }
  75.  
  76. void solve()
  77. {
  78.     int n;
  79.     cin >> n;
  80.     int a[n];
  81.     for(int i = 0; i < n; i++) 
  82.         cin >> a[i];
  83.     sort(a, a + n);
  84.    
  85.     node *root = new node;
  86.     node *te = root;
  87.     te = build(te, a, 0, n - 1);
  88.     node *tem0 = root;
  89.     int res = pre(tem0);
  90.     cout << el << res;
  91.     cout << el;
  92. }
  93.  
  94. int main()
  95. {
  96.     int t = 1;
  97.     cin >> t;
  98.     while(t--)
  99.     {
  100.         solve();
  101.     }
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement