I have a BinarySearchTree struct:
struct BSTNode {
int value;
BSTNode *left = nullptr;
BSTNode *right = nullptr;
};
struct BST {
BSTNode *root = nullptr;
};
And some functions to work with this tree:
BSTNode **findPosition(BSTNode *node, int value) {
if (value < node->value) {
if (node->left) {
return findPosition(node->left, value);
} else {
return &node->left;
}
}
if (value > node->value) {
if (node->right) {
return findPosition(node->right, value);
} else {
return &node->right;
}
}
return &node;
}
void remove(BSTNode** position, int value) {
if ((*position)->left == nullptr && (*position)->right == nullptr) {
delete (*position);
*position= nullptr;
}
}
void remove(BST &bst, int value) {
BSTNode **position = findPosition(bst.root, value);
if (*position != nullptr) {
remove(position,value);
}
}
void add(BSTNode *node, int value) {
BSTNode **position = findPosition(node, value);
BSTNode *newNode = new BSTNode;
newNode->value = value;
*position = newNode;
}
void add(BST &bst, int value) {
if (!bst.root) {
BSTNode *root = new BSTNode;
root->value = value;
bst.root = root;
} else {
add(bst.root, value);
}
}
Adding works fine, but removing elements work strangely (now it should work only for leaf nodes). It just sets the value of the node to zero. I think that the problem is in my use of pointers.
What I am doing wrong?