Advertisement
tungSfer

dsa_level_traversals

May 15th, 2021
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 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. }
  27.  
  28. node *addL(node *p, int x)
  29. {
  30.     node *temp = p;
  31.     node *te1 = create(x);
  32.     temp->l = te1;
  33.     return temp;
  34. }
  35.  
  36. node *addR(node *p, int x)
  37. {
  38.     node *temp = p;
  39.     node *te1 = create(x);
  40.     temp->r = te1;
  41.     return temp;
  42. }
  43.  
  44. void travel(node *root, int x, int y, char c)
  45. {
  46.     node *p = root;
  47.     if(p->val == x)
  48.     {
  49.         if(c == 'L')
  50.             p = addL(p, y);
  51.         else
  52.             p = addR(p, y);
  53.     }
  54.     if(p->l != NULL)
  55.         travel(p->l, x, y, c);
  56.     if(p->r != NULL)
  57.         travel(p->r, x, y, c);
  58. }
  59.  
  60. void pre(node *root)
  61. {
  62.     node *p = root;
  63.     cout << p->val << " ";
  64.     if(p->l != NULL)
  65.         pre(p->l);
  66.     if(p->r != NULL)
  67.         pre(p->r);
  68. }
  69.  
  70. void level(node *root)
  71. {
  72.     node *p = root;
  73.     queue<node*> q;
  74.     q.push(p);
  75.     while(!q.empty())
  76.     {
  77.         cout << q.front()->val << " ";
  78.         if(q.front()->l != NULL)
  79.             q.push(q.front()->l);
  80.         if(q.front()->r != NULL)
  81.             q.push(q.front()->r);
  82.         q.pop()
  83.     }
  84. }
  85.  
  86. void solve()
  87. {
  88.     int n;
  89.     cin >> n;
  90.     int a, b;
  91.     char c;
  92.     cin >> a >> b >> c;
  93.     n--;
  94.     node *root = create(a);
  95.     node *te = root;
  96.     travel(te, a, b, c);
  97.     while(n--)
  98.     {
  99.         cin >> a >> b >> c;
  100.         travel(te, a, b, c);
  101.     }
  102.     node *tem0 = root, *tem1 = root, *tem2 = root, *tem3 = root;
  103.     level(tem0);
  104.     cout << el;
  105. //  in(tem1);
  106. //  cout << el;
  107. //  pre(tem2);
  108. //  cout << el;
  109. //  post(tem3);
  110. //  cout << el;
  111. }
  112.  
  113. int main()
  114. {
  115.     int t = 1;
  116.     cin >> t;
  117.     while(t--)
  118.     {
  119.         solve();
  120.     }
  121.     return 0;
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement