Advertisement
35657

Untitled

Jun 23rd, 2023 (edited)
716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Set {
  6.  
  7. public:
  8.  
  9.     struct Node {
  10.         int value = 0;
  11.         Node* left = nullptr;
  12.         Node* right = nullptr;
  13.         Node* parent = nullptr;
  14.     };
  15.  
  16.     void Insert(const int& val) {
  17.         if (root == nullptr) {
  18.             root = new Node{ val, nullptr, nullptr, nullptr };
  19.             size++;
  20.             return;
  21.         }
  22.         Node* parent = nullptr;
  23.         Node* node = root;
  24.         while (node != nullptr && node->value != val) {
  25.             parent = node;
  26.             node = node->value > val ? node->left : node->right;
  27.         }
  28.         if (node == nullptr) {
  29.             Node* temp = new Node{ val, nullptr, nullptr, parent };
  30.  
  31.             parent->value > val ? parent->left = temp : parent->right = temp;
  32.             size++;
  33.         }
  34.     }
  35.  
  36.     void Print() {
  37.         Print(root);
  38.         cout << endl;
  39.     }
  40.  
  41.     void Print(Node* node) {
  42.         if (node != nullptr) {
  43.             Print(node->left);
  44.             cout << node->value << " ";
  45.             Print(node->right);
  46.         }
  47.     }
  48.  
  49.     int Size() {
  50.         return size;
  51.     }
  52.  
  53. private:
  54.     int size = 0;
  55.     Node* root = nullptr;
  56. };
  57.  
  58.  
  59. void main() {
  60.     Set tr;
  61.     srand(time(NULL));
  62.     int arr[]{ 45, 30, 50, 27, 39, 90, 30, 15, 70, 93 };
  63.     for (int i = 0; i < 10; i++) {
  64.         //int val = rand() % 100;
  65.         int val = arr[i];
  66.         cout << val << " ";
  67.         tr.Insert(val);
  68.     }
  69.     cout << endl << endl;
  70.  
  71.     tr.Print();
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement