Advertisement
tungSfer

BST

May 23rd, 2021
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 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 *addL(node *p, int x)
  30. {
  31.     node *temp = p;
  32.     node *te1 = create(x);
  33.     temp->l = te1;
  34.     return temp;
  35. }
  36.  
  37. node *addR(node *p, int x)
  38. {
  39.     node *temp = p;
  40.     node *te1 = create(x);
  41.     temp->r = te1;
  42.     return temp;
  43. }
  44.  
  45. void travel(node *root, int x)
  46. {
  47.     node *p = root;
  48.     if(p->val < x && p->l == NULL)
  49.         p = addL(p, x);
  50.     else if(p->val > x && p->r == NULL)
  51.         p = addR(p, x);
  52.     else if(p->val < x && p->l != NULL)
  53.         travel(p->l, x);
  54.     else if(p->val > x && p->r != NULL)
  55.         travel(p->r, x);
  56. }
  57.  
  58. void post(node *root)
  59. {
  60.     node *p = root;
  61.     if(p->r != NULL)
  62.         post(p->r);
  63.     if(p->l != NULL)
  64.         post(p->l);
  65.    
  66.     cout << p->val << " ";
  67. }
  68.  
  69. void solve()
  70. {
  71.     int n;
  72.     cin >> n;
  73.     int a;
  74.     cin >> a;
  75.     n--;
  76.     node *root = create(a);
  77.     node *te = root;
  78.     while(n--)
  79.     {
  80.         cin >> a;
  81.         travel(te, a);
  82.     }
  83.     node *tem0 = root;
  84.     post(tem0);
  85.     cout << el;
  86. }
  87.  
  88. int main()
  89. {
  90.     int t = 1;
  91.     cin >> t;
  92.     while(t--)
  93.     {
  94.         solve();
  95.     }
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement