В следующем коде удаление вершины из дерева Tree работает некорректно, и теряются сразу несколько вершин. В частности, при удалении корневого элемента теряется всё правое поддерево:
#include
#include
#include
#include
#include
#include
using namespace std;
struct VendorCode
{
long long int vendorcode;
bool correct = true;
VendorCode(long long int vc) {
long long int n = vc;
int c = 0;
while (n != 0) {
c++;
n /= 10;
}
if (c == 8) {
vendorcode = vc;
}
else {
correct = false;
vendorcode = 10000000;
}
}
};
struct ProdName {
std::string productname;
ProdName(std::string pn) : productname(pn) {}
};
struct TIN
{
long long int tin;
bool correct = true;
TIN(long long int t) {
long long int n = t;
int c = 0;
while (n != 0)
{
c++;
n /= 10;
}
if (c == 10)
{
tin = t;
}
else
{
correct = false;
tin = 1000000000;
}
}
};
struct Date {
int day;
int month;
int year;
bool correct = true;
Date(int d, int m, int y) {
if (y > 2024 || y < 2000)
correct = false;
else
{
switch (m)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if (d < 1 || d > 31)
correct = false;
break;
case 4: case 6: case 9: case 11:
if (d < 1 || d > 30)
correct = false;
break;
case 2:
if (d < 1 || d > 28)
correct = false;
break;
default:
correct = false;
break;
}
}
if (correct)
{
day = d;
month = m;
year = y;
}
else
{
day = 1;
month = 1;
year = 2000;
}
}
};
struct Sorts {
VendorCode vendorcodes;
ProdName productnames;
TIN tins;
Date dates;
int firstHash;
Sorts(const VendorCode& vc, const ProdName& pn, const TIN& t, const Date& d) : vendorcodes(vc), productnames(pn), tins(t), dates(d), firstHash(0) {}
};
struct Cell {
Sorts sorts;
int flag;
int firstHash;
Cell() : sorts(VendorCode(0), ProdName(“”), TIN(0), Date(1, 1, 2000)), flag(0), firstHash(0) {}
};
class HashTable
{
private:
int digitsCount(int n)
{
int c = 0;
while (n != 0)
{
c++;
n /= 10;
}
return c;
}
int hash1(int key1, int key2, int key3, int n)
{
int d = digitsCount(n - 1);
int l = digitsCount(key1);
int e = (2 * l - d) / 2;
int r = pow(10, e);
int h1 = (key1 * key1) / r;
int mod = pow(10, d);
h1 %= mod;
l = digitsCount(key2);
e = (2 * l - d) / 2;
r = pow(10, e);
int h2 = (key2 * key2) / r;
mod = pow(10, d);
h2 %= mod;
l = digitsCount(key3);
e = (2 * l - d) / 2;
r = pow(10, e);
int h3 = (key3 * key3) / r;
mod = pow(10, d);
h3 %= mod;
int h = (h1 + h2 + h3) % n;
return h;
}
int hash2(int key1, int key2, int key3, int j, int k, int n)
{
int hash = (hash1(key1, key2, key3, n) + j * k) % n;
return hash;
}
int collisionInsert(int key1, int key2, int key3, int n, int hash)
{
int h = hash;
int j = 0;
int k = 3;
do
{
if (table[h].sorts.dates.day == key1 && table[h].sorts.dates.month == key2 && table[h].sorts.dates.year == key3)
return -2;
if (table[h].flag != 1)
{
return h;
}
else
{
h = hash2(key1, key2, key3, j, k, n);
++j;
}
} while (j <= n);
return -1;
}
int collisionSearch(int key1, int key2, int key3, int n, int hash)
{
int h = hash;
int j = 0;
int k = 3;
do
{
if (table[h].sorts.dates.day == key1 && table[h].sorts.dates.month == key2 && table[h].sorts.dates.year == key3)
{
return h;
}
else
{
h = hash2(key1, key2, key3, j, k, n);
++j;
}
} while (j != n);
return -1;
}
public:
std::vector table;
bool isEmpty()
{
for (int i = 0; i < table.size(); i++)
{
if (table[i].flag == 1)
return false;
}
return true;
}
int insertItem(Sorts s)
{
int n = table.size();
int key1 = s.dates.day;
int key2 = s.dates.month;
int key3 = s.dates.year;
int hash = hash1(key1, key2, key3, n);
s.firstHash = hash;
if (table[hash].flag != 1)
{
table[hash].sorts = s;
table[hash].firstHash = s.firstHash;
table[hash].flag = 1;
return 0;
}
else
{
int secondhash = collisionInsert(key1, key2, key3, n, hash);
if (secondhash == -2)
{
std::cout << “Item is already in the table.” << std::endl;
return -2;
}
else if (secondhash == -1)
{
std::cout << “Can’t insert, table is full.” << std::endl;
return -1;
}
else
{
for (int i = 0; i < table.size(); i++)
{
if (table[i].sorts.dates.day == key1 && table[i].sorts.dates.month == key2 && table[i].sorts.dates.year == key3)
return -2;
}
table[secondhash].sorts = s;
table[secondhash].firstHash = s.firstHash;
table[secondhash].flag = 1;
return 1;
}
}
}
int removeItem(int key1, int key2, int key3)
{
int n = table.size();
int hash = hash1(key1, key2, key3, n);
if (table[hash].sorts.dates.day == key1 && table[hash].sorts.dates.month == key2 && table[hash].sorts.dates.year == key3)
{
table[hash].flag = 2;
std::cout << “Removed.” << std::endl;
return 0;
}
else
{
int secondhash = collisionSearch(key1, key2, key3, n, hash);
if (secondhash != -1)
{
if (table[secondhash].flag == 1)
{
table[secondhash].flag = 2;
std::cout << “Removed.” << std::endl;
return 1;
}
}
std::cout << “Can’t remove. Haven’t found item.” << std::endl;
return -1;
}
}
HashTable()
{
Assistant
User
Также учти, что при удалении нужно менять удаляемый элемент на максимальный элемент его левого поддерева
Assistant
В случае, когда удаляемой вершине требуется найти максимальный элемент в левом поддереве и заменить ее этим элементом, вам нужно внести следующее изменение внутри условия, когда у удаляемой вершины есть оба потомка:
cpp
else
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
if (p->right == NULL) {
Node* temp = p->left;
delete p;
p = temp;
h = true;
} else {
Node* temp = p->left;
Node* parent = p;
while (temp->right != NULL)
{
parent = temp;
temp = temp->right;
}
if (parent != p)
parent->right = temp->left;
else
parent->left = temp->left;
p->key = temp->key;
p->ht = temp->ht;
delete temp;
h = true;
}
}
}
void addItem(long long int vc, std::string pn, long long int t, int d, int m, int y)
{
bool h = false;
add(vc, pn, t, d, m, y, root, h);
}
void removeItem(std::string pn, int d, int m, int y)
{
bool h = false;
delet(pn, d, m, y, root, h);
}
int searchItem(std::string pn, int d, int m, int y)
{
bool h = false;
int searchsteps = 0;
searchsteps = search(pn, d, m, y, root, h, searchsteps); // Если не найден, то -1
return searchsteps;
}
for (int i = 0; i < sorts.size(); i++)
{
if (i < sorts.size())
addItem(sorts[i].vendorcodes.vendorcode, sorts[i].productnames.productname, sorts[i].tins.tin, sorts[i].dates.day, sorts[i].dates.month, sorts[i].dates.year);
}
}
};
Для исправления проблемы с некорректным удалением вершин из дерева Tree вам необходимо внести следующие изменения в функцию delet класса Tree:
cpp
void delet(std::string pn, int d, int m, int y, Node*& p, bool& h)
{
Node* q;
if (p == NULL)
{
h = false;
std::cout << "Can't remove. Haven't found item." << std::endl;
}
else if (pn < p->key)
{
delet(pn, d, m, y, p->left, h);
if (h)
balance1(p, h);
}
else if (pn > p->key)
{
delet(pn, d, m, y, p->right, h);
if (h)
balance2(p, h);
}
else
{
if (p->left == NULL && p->right == NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
delete p;
p = NULL;
h = true;
}
}
else if (p->left != NULL && p->right == NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
Node* temp = p->left;
delete p;
p = temp;
h = true;
}
}
else if (p->left == NULL && p->right != NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
Node* temp = p->right;
delete p;
p = temp;
h = true;
}
}
else
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
Node* temp = p->left;
Node* parent = p;
while (temp->right != NULL)
{
parent = temp;
temp = temp->right;
}
if (parent != p)
parent->right = temp->left;
else
parent->left = temp->left;
p->key = temp->key;
p->ht = temp->ht;
delete temp;
h = true;
}
}
}
if (h && p != NULL)
{
if (p->balance == -2)
{
if (p->left->balance == 1)
balance2(p, h);
else
balance1(p, h);
}
else if (p->balance == 2)
{
if (p->right->balance == -1)
balance1(p, h);
else
balance2(p, h);
}
}
}
Эти изменения помогут правильно удалить вершины из дерева и поддерживать его сбалансированным после операции удаления.
Это изменение позволит заменить удаляемую вершину максимальным элементом из ее левого поддерева, если у вершины есть оба потомка.
Для полного понимания работы метода delet в классе Tree, включая изменения, связанные с заменой удаляемого элемента на максимальный элемент из его левого поддерева, вот исправленный метод целиком:
cpp
void delet(std::string pn, int d, int m, int y, Node*& p, bool& h)
{
Node* q;
if (p == NULL)
{
h = false;
std::cout << "Can't remove. Haven't found item." << std::endl;
}
else if (pn < p->key)
{
delet(pn, d, m, y, p->left, h);
if (h)
balance1(p, h);
}
else if (pn > p->key)
{
delet(pn, d, m, y, p->right, h);
if (h)
balance2(p, h);
}
else
{
if (p->left == NULL && p->right == NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
delete p;
p = NULL;
h = true;
}
}
else if (p->left != NULL && p->right == NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
Node* temp = p->left;
delete p;
p = temp;
h = true;
}
}
else if (p->left == NULL && p->right != NULL)
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
Node* temp = p->right;
delete p;
p = temp;
h = true;
}
}
else
{
p->ht.removeItem(d, m, y);
if (p->ht.isEmpty())
{
if (p->right == NULL) {
Node* temp = p->left;
delete p;
p = temp;
h = true;
} else {
Node* temp = p->left;
Node* parent = p;
while (temp->right != NULL)
{
parent = temp;
temp = temp->right;
}
if (parent != p)
parent->right = temp->left;
else
parent->left = temp->left;
p->key = temp->key;
p->ht = temp->ht;
delete temp;
h = true;
}
}
}
}
if (h && p != NULL)
{
if (p->balance == -2)
{
if (p->left->balance == 1)
balance2(p, h);
else
balance1(p, h);
}
else if (p->balance == 2)
{
if (p->right->balance == -1)
balance1(p, h);
else
balance2(p, h);
}
}
}