Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Set {
- public:
- struct Node {
- int value = 0;
- Node* left = nullptr;
- Node* right = nullptr;
- Node* parent = nullptr;
- };
- void Insert(const int& val) {
- if (root == nullptr) {
- root = new Node{ val, nullptr, nullptr, nullptr };
- size++;
- return;
- }
- Node* parent = nullptr;
- Node* node = root;
- while (node != nullptr && node->value != val) {
- parent = node;
- node = node->value > val ? node->left : node->right;
- }
- if (node == nullptr) {
- Node* temp = new Node{ val, nullptr, nullptr, parent };
- parent->value > val ? parent->left = temp : parent->right = temp;
- size++;
- }
- }
- void Print() {
- Print(root);
- cout << endl;
- }
- void Print(Node* node) {
- if (node != nullptr) {
- Print(node->left);
- cout << node->value << " ";
- Print(node->right);
- }
- }
- int Size() {
- return size;
- }
- private:
- int size = 0;
- Node* root = nullptr;
- };
- void main() {
- Set tr;
- srand(time(NULL));
- int arr[]{ 45, 30, 50, 27, 39, 90, 30, 15, 70, 93 };
- for (int i = 0; i < 10; i++) {
- //int val = rand() % 100;
- int val = arr[i];
- cout << val << " ";
- tr.Insert(val);
- }
- cout << endl << endl;
- tr.Print();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement