Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Практики / ПР5 / СД_П5

.pdf
Скачиваний:
0
Добавлен:
27.06.2025
Размер:
477.54 Кб
Скачать

Заключение

В ходе работы было создано бинарное дерево поиска с поддержкой основных операций: добавление, удаление, очистка, вывод, поиск максимального элементов.

11

Приложение А (обязательное)

class Node

{

public int Data; public Node Left; public Node Right;

public Node(int data)

{

Data = data; Left = null; Right = null;

}

}

class Tree

{

private Node Root;

public Tree()

// инициализация пустого дерева

{

 

Root = null;

 

}

 

public bool AddItem(int a)

{

if (Root == null)

{

12

Root = new Node(a); // если пусто, то становится корнем return true;

}

return AddItemRecursive(Root, a);

}

private bool AddItemRecursive(Node current, int a)

{

if (a == current.Data) // если элмент уже есть return false;

if (a < current.Data) // если добавляемый меньше текущего, то добавляем влево

{

if (current.Left == null)

{

current.Left = new Node(a); return true;

}

return AddItemRecursive(current.Left, a);

}

else // если добавляемый больше текущего, то добавляем вправо

{

if (current.Right == null)

{

current.Right = new Node(a); return true;

}

return AddItemRecursive(current.Right, a); 13

}

}

public bool RemoveItem(int a)

{

bool found;

Root = RemoveItemRecursive(Root, a, out found); return found;

}

private Node RemoveItemRecursive(Node current, int a, out bool found)

{

found = false;

if (current == null) return null; // если элемента нет

if (a < current.Data) // если меньше текущего, то идем в левую ветку

{

current.Left = RemoveItemRecursive(current.Left, a, out found);

}

else if (a > current.Data) // если больше текущего, то идем в правую ветку

{

current.Right = RemoveItemRecursive(current.Right, a, out found);

}

else

{

found = true;

// если 1 элемент или нет дочерних

14

if (current.Left == null) return current.Right; if (current.Right == null) return current.Left;

// если 2 элемента, то ищем меньший current.Data = FindMinValue(current.Right);

current.Right = RemoveItemRecursive(current.Right, current.Data, out

found);

}

return current;

}

private int FindMinValue(Node current) // до конца влево, потому-что меньшее

{

while (current.Left != null)

{

current = current.Left;

}

return current.Data;

}

public void Clear()

{

Root = null;

}

public int FindMax()

{

if (Root == null) throw new InvalidOperationException("Дерево пустое"); 15

Node current = Root;

while (current.Right != null) // до конца вправо, потому-что большее

{

current = current.Right;

}

return current.Data;

}

public void Print() //в ширину

{

if (Root == null)

{

Console.WriteLine("Дерево пустое"); return;

}

Queue<Node> queue = new Queue<Node>(); // хранилище узлов queue.Enqueue(Root);

while (queue.Count > 0) // пока есть узлы - пашем

{

Node current = queue.Dequeue(); // вывод первого узла Console.Write(current.Data + " ");

if (current.Left != null) queue.Enqueue(current.Left); // если есть потомок слева - в очередь

if (current.Right != null) queue.Enqueue(current.Right); // если есть справа- в очередь

}

16

Console.WriteLine(); // новая строка

}

}

class Program

{

static void Main()

{

Tree tree = new Tree(); bool running = true;

while (running)

{

Console.WriteLine("\nВыберите действие:"); Console.WriteLine("1 - Добавить элемент в дерево"); Console.WriteLine("2 - Удалить элемент из дерева"); Console.WriteLine("3 - Очистить дерево"); Console.WriteLine("4 - Показать дерево"); Console.WriteLine("5 - Найти максимальный элемент"); Console.WriteLine("6 - Выйти"); Console.Write("Введите ваш выбор: ");

int choice = int.Parse(Console.ReadLine());

switch (choice)

{

case 1:

17

Console.Write("Введите элемент для добавления: "); int addValue = int.Parse(Console.ReadLine());

if (tree.AddItem(addValue)) Console.WriteLine("Элемент успешно добавлен.");

else

Console.WriteLine("Элемент уже существует в дереве."); break;

case 2:

Console.Write("Введите элемент для удаления: "); int removeValue = int.Parse(Console.ReadLine()); if (tree.RemoveItem(removeValue))

Console.WriteLine("Элемент успешно удален."); else

Console.WriteLine("Элемент не найден."); break;

case 3: tree.Clear();

Console.WriteLine("Дерево очищено."); break;

case 4: Console.WriteLine("Дерево:"); tree.Print();

break;

case 5:

18

try

{

Console.WriteLine("Самый большой элемент в дереве: " + tree.FindMax());

}

catch (InvalidOperationException e)

{

Console.WriteLine(e.Message);

}

break;

case 6:

running = false; break;

default:

Console.WriteLine("Неверный выбор, попробуйте снова."); break;

}

}

}

}

19

Соседние файлы в папке ПР5