Advertisement
smatskevich

Lesson4

Oct 17th, 2024 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <cassert>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. struct Node {
  8.   int Data;
  9.   Node* Left;
  10.   Node* Right;
  11.   Node(int data) : Data(data), Left(nullptr), Right(nullptr) {}
  12. };
  13.  
  14. int DeleteMin(Node*& node) {
  15.   assert(node != nullptr);
  16.   if (node->Left == nullptr) {
  17.     Node* todel = node;
  18.     node = node->Right;
  19.     int ans = todel->Data;
  20.     delete todel;
  21.     return ans;
  22.   }
  23.   return DeleteMin(node->Left);
  24. }
  25.  
  26. void DeleteNode(Node*& node) {
  27.   if (node->Left == nullptr) {
  28.     Node* todel = node;
  29.     node = node->Right;
  30.     delete todel;
  31.   } else if (node->Right == nullptr) {
  32.     Node* todel = node;
  33.     node = node->Left;
  34.     delete todel;
  35.   } else {
  36.     int mn = DeleteMin(node->Right);
  37.     node->Data = mn;
  38.   }
  39. }
  40.  
  41. // Удаление. Возвращает false, если нет узла с заданным ключом.
  42. bool Delete(Node*& node, int value ) {
  43.   if (node == 0) return false;
  44.   if (node->Data == value) { // Нашли, удаляем.
  45.     DeleteNode(node);
  46.     return true;
  47.   }
  48.   return Delete(node->Data > value ? node->Left : node->Right, value);
  49. }
  50.  
  51. void Print(Node* node, string prefix) {
  52.   if (node == nullptr) return;
  53.   Print(node->Right, prefix + "  ");
  54.   cout << prefix << node->Data << "\n";
  55.   Print(node->Left, prefix + "  ");
  56. }
  57.  
  58. int main() {
  59.   Node* root = new Node(6);
  60.   root->Left = new Node(2);
  61.   root->Right = new Node(10);
  62.   root->Right->Left = new Node(8);
  63.   Print(root, "");
  64.   Delete(root, 6);
  65.   Print(root, "");
  66.   return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement