Advertisement
Technoblade777

Софа деревья

May 28th, 2023 (edited)
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. //создаем стрктуру дерева
  5. struct tree{
  6.     int info;
  7.     tree *right, *left;
  8. };
  9.  
  10. //фукнция дерева
  11. void add_node(tree *node, int n)
  12. {
  13.     if(n<node->info)
  14.     {
  15.         if(node->left==NULL)
  16.         {
  17.             tree *r = new tree;
  18.             r->info = n;
  19.             node->left = r;
  20.         }
  21.         else{add_node(node->left, n);}
  22.     }
  23.     else
  24.     {
  25.         if(node->right==NULL)
  26.         {
  27.             tree *r = new tree;
  28.             r->info = n;
  29.             node->right = r;
  30.         }
  31.         else{add_node(node->right, n);}
  32.     }
  33. }
  34.  
  35. void LNR(tree *node)
  36. {
  37.     if(node==NULL){return;}
  38.     else
  39.     {
  40.         LNR(node->left);
  41.         cout << node->info << " ";
  42.         LNR(node->right);
  43.     }
  44. }
  45. int main()
  46. {
  47.     int n;
  48.     cout << "Введите длину массива: "; cin>>n;
  49.     int *a = new int[n];
  50.     for(int i = 0; i < n; i++)
  51.     {
  52.         cin >> a[i];
  53.     }
  54.  
  55.     //объявляем корень дерева
  56.     tree *root = new tree;
  57.     int x;
  58.     int i = 0;
  59.     //проверка корневого элемента на четность
  60.     while(i!=n)
  61.     {
  62.         if(a[i]%2==0){x=a[i]; break;}
  63.         i++;
  64.         if(i==n){cout<<"В исходном массиве отсутствуют четные числа"; return 0;}
  65.     }
  66.     root->left = NULL; root->right = NULL;
  67.     root->info = x;
  68.     i++;
  69.  
  70.     //проверка остальной части элементов массива на четность
  71.     while(i<n)
  72.     {
  73.         x = a[i];
  74.         if(x%2==0){add_node(root, x);}
  75.         i++;
  76.     }
  77.  
  78.     //вывод в отсортированном виде
  79.     LNR(root);
  80.  
  81.     return 0;
  82. }
  83.  
  84.  
  85.  
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement