我目前正在为作业编写代码,但它一直给我单元测试区域的错误。我所要做的就是实现一个添加功能,删除功能和搜索功能。我已经编写了代码,但在单元测试方面看不出它有什么问题。这是我的代码:
class Node {
public:
Node *left;
Node *right;
int value;
Node(int value) {
this->value = value;
left = nullptr;
right = nullptr;
}
};
#include "node.h"
class BST {
public:
Node *root;
BST();
bool add(int value);
bool remove(int value);
bool search(int value);
};
#include "BST.h"
BST::BST()
{
root = nullptr;
}
bool BST::add(int value)
{
Node* n = new Node(value);
if (root == nullptr)
root = n;
else {
Node* curr = root;
while (curr != nullptr) {
if (value == curr->value)
return false;
if (value < curr->value) {
if (curr->left == nullptr) {
curr->left = n;
break;
}
else
curr = curr->left;
}
else {
if (curr->right == nullptr) {
curr->right = n;
break;
}
else
curr = curr->right;
}
}
}
return true;
}
bool BST::remove(int value)
{
Node* curr = root;
Node* parent = nullptr;
while (curr != nullptr) {
if (curr->value == value)
break;
parent = curr;
if (value < curr->value)
curr = curr->left;
else
curr = curr->right;
}
if (curr == nullptr)
return false;
if (curr->left == nullptr && curr->right == nullptr) {
if (curr == root)
root = nullptr;
else {
if (parent->left == curr)
parent->left = nullptr;
else
parent->right = nullptr;
}
delete curr;
}
else if (curr->left == nullptr && curr->right != nullptr) {
if (curr == root)
root = curr->right;
else {
if (parent->left == curr)
parent->left = curr->right;
else
parent->right = curr->right;
}
delete curr;
}
else if (curr->left != nullptr && curr->right == nullptr) {
if (curr == root)
root = curr->left;
else {
if (parent->left == curr)
parent->left = curr->left;
else
parent->right = curr->left;
}
delete curr;
}
else {
Node* succ = curr->right;
while (succ->left != nullptr)
succ = succ->left;
int succVal = succ->value;
remove(succVal);
curr->value = succVal;
}
return true;
}
bool BST::search(int value)
{
Node* curr = root;
while (curr != nullptr) {
if (value < curr->value)
curr = curr->left;
else if (value > curr->value)
curr = curr->right;
else
return true;
}
return false;
}
显示单元测试错误
main.cpp: In function ‘bool testPassed()’:
main.cpp:42:12: warning: unused variable ‘one’ [-Wunused-variable]
bool one = foo->add(943) == false;
^~~ main.cpp:43:12: warning: unused variable ‘two’ [-Wunused-variable]
bool two = foo->root->left->right->right->left->value == 230;
^~~ main.cpp:44:12: warning: unused variable ‘three’ [-Wunused-variable]
bool three = foo->root->right->left->right->value == 919;
^~~~~ main.cpp:46:12: warning: unused variable ‘four’ [-Wunused-variable]
bool four = foo->search(121) == true;
^~~~ main.cpp:59:17: error: ‘one’ was not declared in this scope
std::cout << one << two << three << four << five << six << seven << eight << nine << std::endl;
^~~
我不确定我做错了什么,任何建议或提示都会有所帮助。谢谢。