1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
void BST::removeAllMatches(Book &aBook)
{
char author[25];
cout << "Enter the author to remove from the list: " << endl;
cin.get(author, 25, '\n');
removeAllMatches(root, author, aBook);
}
bool BST::removeAllMatches(Node *&currRoot, const char *author, Book &aBook)
{
int temp = 0;
char match[25];
char key[50];
bool flag = false;
if (currRoot)
{
currRoot->data.getAuthor(match);
temp = strcmp(author, match);
if (temp == 0)
{
currRoot->data.getKeyword(key);
removeBook(currRoot, key, aBook);
flag = true;
}
else if (temp < 0)
{
currRoot = currRoot->left;
currRoot->data.getKeyword(key);
removeAllMatches(currRoot->left, key, aBook);
}
else
{
currRoot = currRoot->right;
currRoot->data.getKeyword(key);
removeAllMatches(currRoot->right, key, aBook);
}
}
return flag;
}
// remove single Book by keyword
bool BST::removeBook(char *key, Book &removeEntry)
{
return removeBook(root, key, removeEntry);
}
// recursive single removal helper
bool BST::removeBook(Node *&currRoot, char *key, Book &removeEntry)
{
char keyword[50];
if (!currRoot)
return false;
currRoot->data.getKeyword(keyword);
int temp = strcmp(key, keyword);
if (temp == 0)
{
removeEntry = currRoot->data;
deleteNode(currRoot);
size--;
return true;
}
else if (temp < 0) // remove from left tree
{
return removeBook(currRoot->left, key, removeEntry);
}
else // remove from right tree
{
return removeBook(currRoot->right, key, removeEntry);
}
}
void BST::deleteNode(Node *&target)
{
if (!target->left && !target->right)
{
delete target;
target = nullptr;
}
else if (!target->right)
{
Node *temp = target;
target = target->left;
delete temp;
temp = nullptr;
}
else if (!target->left)
{
Node *temp = target;
target = target->right;
delete temp;
temp = nullptr;
}
else
{
// find the inorder successor
Node *prev = nullptr;
Node *curr = target->right;
while (curr->left)
{
prev = curr;
curr = curr->left;
}
target->data = curr->data;
if (!prev)
{
target->right = curr->right;
}
else
{
prev->left = curr->right;
}
delete curr;
}
}
|