35657

Untitled

Mar 28th, 2024 (edited)
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 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;
  11.         Node* left;
  12.         Node* right;
  13.         Node* parent;
  14.     };
  15.  
  16.     Set() : root_(nullptr), size_(0) {}
  17.  
  18.     void insert(const int& val) {
  19.         if (root_ == nullptr) {
  20.             root_ = new Node{ val, nullptr, nullptr, nullptr };
  21.             size_++;
  22.             return;
  23.         }
  24.         Node* parent = nullptr;
  25.         Node* node = root_;
  26.         while (node != nullptr && node->value != val) {
  27.             parent = node;
  28.             node = node->value > val ? node->left : node->right;
  29.         }
  30.         if (node == nullptr) {
  31.             node = new Node{ val, nullptr, nullptr, parent };
  32.             parent->value > val ? parent->left = node : parent->right = node;
  33.             size_++;
  34.         }
  35.     }
  36.  
  37.     void print() {
  38.         print(root_);
  39.         cout << endl;
  40.     }
  41.  
  42. private:
  43.  
  44.     void print(Node* node) {
  45.         if (node != nullptr) {
  46.             print(node->left);
  47.             cout << node->value << " ";
  48.             print(node->right);
  49.         }
  50.     }
  51.  
  52.     Node* root_;
  53.     int size_;
  54. };
  55.  
  56.  
  57. int main() {
  58.    
  59.     int arr[]{ 45,30,50,27,39,90,15,70,103 };
  60.  
  61.     Set st;
  62.  
  63.     for (int i = 0; i < 9; i++) {
  64.         st.insert(arr[i]);
  65.     }
  66.  
  67.     st.print();
  68. }
Add Comment
Please, Sign In to add comment