I've been trying to do unit testing for my AVL Tree class and when I call the "depth()" function which calls a recursive "depth(...)" I get the following exception Code: Error Code: C0000005
This is my code for the depth function:
int Tree::depth()
{
int currentDepth = -1;
if (this->isEmpty() == false) {
currentDepth = depth(this->root, currentDepth);
}
return currentDepth;
}
int Tree::depth(Node* node, int currentDepth)
{
int nodeDepth = currentDepth;
if (node->left != nullptr) { // <-------------- Error happens at this line
nodeDepth = depth(node->left, currentDepth);
}
if (node->right != nullptr) {
nodeDepth = depth(node->right, currentDepth);
}
return nodeDepth + 1;
}
I've looked up what can cause this error and most people say it is due to an uninitialized pointer but I've tried many ways of initializing the pointer to no avail. This is what I have now:
struct Node {
public:
TreeElement* element;
Node* parent;
Node* left;
Node* right;
Node(TreeElement* element, Node* parent) {
this->element = element;
this->parent = parent;
this->left = nullptr; // <------------ This part here
this->right = nullptr;
}
~Node(){}
};
When I debug the test it ends up lifting this exception: Read access violation
I'm trying to find out how to fix this error.
Here's my Unit test and code to add a node to the tree in case you need it
Test Method:
TEST_METHOD(WHEN_anElementIsAddedToATree_THEN_itHasCorrectDepth)
{
// Arrange
Tree tree;
Word* element = new Word(ANY_WORD);
// Act
tree.add(element);
// Assert
int ANSWER = tree.depth();
const int EXPECTED_ANSWER = 0;
Assert::AreEqual(ANSWER, EXPECTED_ANSWER);
}
Add Function:
void Tree::add(TreeElement* element)
{
if (this->isEmpty()) {
Node node = Node(element, nullptr);
this->root = &node;
}
else if (this->find(element) > -1){
throw "Cet élément est déjà présent";
}
else {
add(element, this->root);
}
}
void Tree::add(TreeElement* element, Node* node)
{
if (element->isBiggerThan(node->element)) {
if (node->right != nullptr) {
add(element, node->right);
}
else {
node->right = &Node(element, node);
}
}
else {
if (node->left != nullptr) {
add(element, node->left);
}
else {
node->left = &Node(element, node);
}
}
}