лаба_5_бинарные деревья вариант
.docxБелорусский государственный университет
информатики и радиоэлектроники
Кафедра экономический информатики
Основы алгоритмизации и программирования
Бинарные деревья
Студент Рушева М.В.
Группа 972304
Минск,2020
1)Задание
Разработать проект для обработки дерева поиска, каждый элемент которого содержит целочисленный ключ и строку текста, содержащую, например, ФИО и номер паспорта. В программе должны быть реализованы следующие возможности:
- создание дерева;
- добавление новой записи;
- поиск информации по заданному ключу;
- удаление информации с заданным ключом;
- вывод информации;
- решение индивидуального задания;
- освобождение памяти при выходе из программы.
Задание варианта 5 : определить число узлов на каждом уровне дерева.
2)Код
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <conio.h>
#include <time.h>
int count = 0;
typedef struct {
char name[15];
char surname[15];
char patronymic[15];
int premia;
} School;
typedef struct TREE {
int key;
School sotr;
struct TREE* right;
struct TREE* left;
struct TREE* root;
}TREE;
TREE* create_tree(TREE* tree)
{
TREE* root = (TREE*)malloc(sizeof(TREE));
root->left = root->right = NULL;
root->root = NULL;
root->key = 10;
tree = root;
return tree;
}
int get(char* str)
{
int index = 0;
char ch;
do
{
ch = _getch();
if (ch == 8)
{
str[index] = 0;
index--;
printf("%c%c%c", '\b', 0, '\b');
}
if (ch == '\r' && index == 0)
{
puts("Некорректный ввод");
system("pause");
for (int i = 0; i < 15; i++)
str[i] = 0;
return 0;
}
if ((ch >= 'а' && ch <= 'я') || (ch >= 'А' && ch <= 'Я') || (ch == 'ё') || (ch == 'Ё'))
{
if (index > 14)
{
puts("Некорректный ввод");
system("pause");
for (int i = 0; i < 15; i++)
str[i] = 0;
return 0;
}
printf("%c", ch);
str[index] = ch;
index++;
}
if (index < 0)
{
puts("Некорректный ввод");
system("pause");
for (int i = 0; i < 15; i++)
str[i] = 0;
return 0;
}
} while (ch != '\r');
if (str[0] >= 'а' && str[0] <= 'я')
{
str[0] = str[0] - 32;
}
if (str[0] == 'ё')
str[0] = 'Ё';
for (int i = 1; i < index; i++)
{
if (str[i] >= 'А' && str[i] <= 'Я')
{
str[i] = str[i] + 32;
}
if (str[i] == 'Ё')
str[i] = 'ё';
}
return 1;
}
void vvod_dereva(School* sotr)
{
for (int i = 0; i < 15; i++)
{
sotr->name[i] = 0;
sotr->surname[i] = 0;
sotr->patronymic[i] = 0;
}
do
{
system("cls");
printf("Введите фамилию:\n ");
} while (!get(sotr->surname));
do
{
printf("\nВведите имя:\n ");
} while (!get(sotr->name));
do
{
printf("\nВведите отчество:\n ");
} while (!get(sotr->patronymic));
int premia = 0;
while (premia <= 0)
{
printf("\nВведите размер премии:\n ");
scanf_s("%d", &premia);
if (premia > 0)
{
sotr->premia = premia;
}
else
{
premia = 0;
printf("Повторите попытку\n");
system("pause");
}
while (getchar() != '\n');
}
count++;
}
TREE* kkk(TREE* tree, int key)
{
if (count == 0)
{
vvod_dereva(&tree->sotr);
return tree;
}
else
{
TREE* root1 = tree;
TREE* root2 = NULL;
TREE* node = (TREE*)malloc(sizeof(TREE));
while (root1 != NULL)
{
root2 = root1;
if (key < root1->key)
{
root1 = root1->left;
}
else if (key > root1->key)
{
root1 = root1->right;
}
else return tree;
}
vvod_dereva(&node->sotr);
node->key = key;
node->root = root2;
node->left = node->right = NULL;
if (key < root2->key)
{
root2->left = node;
}
else
{
root2->right = node;
}
return tree;
}
}
void true_otobr(int length, int k)
{
length = k - length;
int i = 0;
while (i < length)
{
printf(" ");
i++;
}
}
void space_int(int length, int k)
{
int number = 0;
while (length >= 10)
{
number++;
length /= 10;
}
number = k - number;
int i = 0;
while (i < number)
{
printf(" ");
i++;
}
}
void print_sotr_school(School* sotr, TREE* root)
{
printf("|| %d", root->key);
space_int(root->key, 3);
printf("||");
int i = strlen(sotr->surname);
printf(" %s", sotr->surname);
true_otobr(i, 15);
printf("||");
i = strlen(sotr->name);
printf(" %s", sotr->name);
true_otobr(i, 15);
printf("||");
i = strlen(sotr->patronymic);
printf(" %s", sotr->patronymic);
true_otobr(i, 15);
printf("||");
printf(" %d", sotr->premia);
space_int(sotr->premia, 7);
printf("||\n");
}
void p_tree(TREE* root)
{
if (root)
{
p_tree(root->right);
print_sotr_school(&root->sotr, root);
p_tree(root->left);
}
}
void keys(TREE* root, int level)
{
if (root)
{
keys(root->right, level + 1);
for (int i = 0; i < level; i++) printf(" ");
printf("%d\n", root->key);
keys(root->left, level + 1);
}
}
int with_key(TREE* root, int key, int print)
{
if (root->key < key)
print = with_key(root->right, key, print);
else if (root->key > key)
print = with_key(root->left, key, print);
else
{
printf("|-----------------------------------------------------------------------|\n");
printf("| Ключ | Фамилия | Имя | Отчество | Премия |\n");
printf("|------|------------------|----------------|------------------|---------|\n");
print_sotr_school(&root->sotr, root);
printf("|-----------------------------------------------------------------------|\n");
print++;
}
return print;
}
TREE* del_t(TREE* root)
{
if (root)
{
del_t(root->left);
del_t(root->right);
free(root);
}
root = 0;
return root;
}
int checkbranch(TREE* root)
{
if (root)
return 0;
}
TREE* findmax(TREE* root)
{
if (root->left)
root = findmax(root->left);
return root;
}
int delk(TREE* root, int key, int del)
{
if (root)
{
if (root->key < key)
del = delk(root->right, key, del);
else if (root->key > key)
del = delk(root->left, key, del);
else
{
if (root->left && root->right) {
TREE* localMax = findmax(root->left);
root->sotr = localMax->sotr;
root->key = localMax->key;
del = delk(localMax, localMax->key, del);
return del;
}
else if (root->left) {
if (root == root->root->left) {
root->root->left = root->left;
}
else {
root->root->right = root->left;
}
}
else if (root->right) {
if (root == root->root->right) {
root->root->right = root->right;
}
else {
root->root->left = root->right;
}
}
else {
if (root->root)
{
if (root == root->root->left) {
root->root->left = NULL;
}
else {
root->root->right = NULL;
}
}
}
del++;
count--;
free(root);
}
}
return del;
}
int fm(int n)
{
int choice;
choice = _getch();
if (choice == 0)
{
choice = _getch();
}
if (choice >= '0' && choice <= '9')
{
if (choice < n)
{
printf("%c", choice);
}
return (choice - '0');
}
}
int* zadanie(TREE* tree, int level, int mas[5])
{
if (tree)
{
zadanie(tree->right, level + 1, mas);
mas[level]++;
zadanie(tree->left, level + 1, mas);
}
return *mas;
}
int main()
{
system("chcp 1251 & cls");
TREE* tree = NULL; TREE* root = NULL;
while (1)
{
system("cls");
int m;
puts("1)Создать дерево");
puts("2)Добавить запись");
puts("3)Удалить одну запись");
puts("4)Вывести запись на экран");
puts("5)Вывести дерево на экран");
puts("6)Удалить дерево полностью");
puts("7)Вариант_5");
puts("8)Выйти из программы");
printf(">> ");
m = fm(9);
switch (m)
{
case 1:
{
tree = create_tree(tree);
break;
}
case 2:
{
if (!tree)
{
printf("Дерево ещё не создано,чтобы добавить запись,нужно его создать...\n");
system("pause");
break;
}
else if (count >= 20)
{
printf("Дерево уже заполнено\n");
system("pause");
break;
}
while (1)
{
srand(time(NULL));
int key = rand() % 20;
if (key == 0 || key == 10)
continue;
else
{
int countbefore = count;
kkk(tree, key);
if (countbefore == count)
continue;
else
break;
}
}
break;
}
case 3:
{
system("cls");
if (!tree)
{
printf("Дерево не создано\n");
system("pause");
}
else if (count == 0)
{
printf("Дерево пусто\n");
system("pause");
}
else
{
int key = 0;
while (key <= 0 || key > 31)
{
system("cls");
printf("Введите ключ : ");
scanf_s("%d", &key);
if (key > 0 && key < 32)
{
int del = 0;
del = delk(tree, key, del);
if (del == 0)
{
printf("Неверный ключ\n");
}
else
{
printf("Запись удалена\n");
}
system("pause");
}
else
{
printf("Неверный ввод\n");
system("pause");
}
while (getchar() != '\n');
}
}
break;
}
case 4:
{
if (!tree)
{
printf("Дерево не создано\n");
system("pause");
}
else if (count == 0)
{
printf("Дерево пусто\n");
system("pause");
}
else
{
int key = 0;
while (key <= 0 || key > 31)
{
system("cls");
printf("Введите ключ : ");
scanf_s("%d", &key);
if (key > 0 && key < 32)
{
int print = 0;
with_key(tree, key, print);
if (print == 0)
{
printf("Неверный ключ\n");
}
system("pause");
}
else
{
printf("Неверный ввод\n");
system("pause");
}
while (getchar() != '\n');
}
}
break;
}
case 5:
{
if (!tree)
{
printf("Дерево не было создано\n");
system("pause");
}
else if (count == 0)
{
printf("Дерево пустое...\n");
system("pause");
}
else
{
system("cls");
printf("|-------------------------------------------------------------------------|\n");
printf("| Ключ | Фамилия | Имя || Отчество | Премия |\n");
printf("|-------|-----------------|-----------------|-----------------|-----------|\n");
p_tree(tree);
printf("|-------------------------------------------------------------------------|\n");
printf("\n\nВзаимодействие узлов в виде \"Дерева\" \n\n\n");
keys(tree, 0);
printf("\n\n");
system("pause");
}
break;
}
case 6:
{
system("cls");
if (!tree)
{
printf("Дерево не было создано\n");
system("pause");
}
else
{
tree = del_t(tree);
count = 0;
printf("Дерево удалено\n");
system("pause");
}
break;
}
case 7:
{
if (tree == NULL)
{
system("cls");
puts("Дерево ещё не создано. Вернитесь и создайте его");
printf("\n");
system("pause");
system("cls");
break;
}
else if (count == 0)
{
system("cls");
puts("Дерево пустое");
printf("\n");
system("pause");
system("cls");
break;
}
system("cls");
int mas[5];
for (int i = 0; i < 5; i++)
mas[i] = 0;
*mas = zadanie(tree, 0, mas);
int i = 0;
while (mas[i] != 0)
{
printf("Количество элементов на %d уровне дерева : %d\n", i, mas[i]);
i++;
}
system("pause & cls");
while (getchar() != '\n');
break;
}
case 8:
{
if (tree)
{
tree = del_t(tree);
count = 0;
}
system("cls");
return 0;
}
default:
{
printf("Неверный ввод\n");
system("pause");
break;
}
}
}
}
3)Консоль
Индивидуальное задание: