ЛБ6 СДА Коваль В В

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

ЛАБОРАТОРНА РОБОТА №6

Тема: Робота з бінарним деревом пошуку


Лістинг:
#include <iostream>
#include <locale>

using namespace std;

struct Node {
int data;
Node* left;
Node* right;
};

Node* createNode(int value) {


Node* newNode = new Node();
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

Node* insert(Node* root, int value) {


if (root == NULL) {
return createNode(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
}
else if (value > root->data) {
root->right = insert(root->right, value);
}

return root;
}

Node* minValueNode(Node* node) {


Node* current = node;

while (current && current->left != NULL) {


current = current->left;
}

return current;
}

Node* deleteNode(Node* root, int value) {


if (root == NULL) {
return root;
}

if (value < root->data) {


root->left = deleteNode(root->left, value);
}
else if (value > root->data) {
root->right = deleteNode(root->right, value);
}
else {
if (root->left == NULL) {
Node* temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
Node* temp = root->left;
delete root;
return temp;
}

Node* temp = minValueNode(root->right);


root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}

return root;
}

void inorder(Node* root) {


if (root == NULL) {
return;
}

inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}

void printMenu() {
cout << "Будь ласка, оберіть опцію:\n"
<< "1. Додати значення\n"
<< "2. Видалити значення\n"
<< "3. Вивести дерево\n"
<< "4. Вийти\n\n";
}

int main() {
setlocale(LC_ALL, ""); // Встановлення української локалізації

Node* root = NULL;


int choice, value;

do {
printMenu();
cin >> choice;

switch (choice) {
case 1:
cout << "Введіть значення для додавання: ";
cin >> value;
root = insert(root, value);
cout << value << " додано до дерева.\n\n ";
break;
case 2:
if (root == NULL) {
cout << "Дерево порожнє.\n\n";
break;
}
cout << "Введіть значення для видалення: ";
cin >> value;
root = deleteNode(root, value);
cout << value << " видалено з дерева.\n\n";
break;
case 3:
cout << "Дерево: ";
inorder(root);
cout << "\n\n";
break;
case 4:
cout << "Вихід...\n";
break;
default:
cout << "Недійсний вибір. Будь ласка, спробуйте ще раз.\n\n";
}
} while (choice != 4);
return 0;
}

Результат:

You might also like