Attached my code for trying to delete a node in bst.
If I want to delete node 1, when specifying tmp = del in "if (del_node->l_ == NULL)", and remove tmp, then del is removed as well, and the tree data is lost. how can I solve this issue?
Example tree:
3
/ \
1 5
\
2
all data members and functions are declared public for simplicity.
void BST::DeleteNode(int data) { BinaryTreeNode* &del_node = BST_Search(head_, data); if (!del_node->l_ && !del_node->r_) { delete del_node; del_node = nullptr; return; } if (del_node->l_ == NULL) { BinaryTreeNode* tmp = del_node; del_node = del_node->r_; tmp = nullptr; delete tmp; return; } if (del_node->r_ == NULL) { BinaryTreeNode* tmp = del_node; del_node = del_node->l_; delete tmp; return; } else { del_node->data_ = smallestRightSubTree(del_node->r_); } } int BST::smallestRightSubTree(BinaryTreeNode* rightroot) { // if rightroot has no more left childs if (rightroot && !rightroot->l_) { int tmpVal = rightroot->data_; BinaryTreeNode* tmp = rightroot; rightroot = rightroot->r_; delete tmp; return tmpVal; } return smallestRightSubTree(rightroot->l_); } int main() { BST bst; bst.BST_Insert(bst.head_, 3); bst.BST_Insert(bst.head_, 5); bst.BST_Insert(bst.head_, 1); bst.BST_Insert(bst.head_, 2); bst.DeleteNode(1); return 0; }
Thanks for help! EDIT: this is how tmp and del_node look like after the line "del_node = del_node->r_)" in the condition "if(del->l = null)"
void BST::BST_Insert(BinaryTreeNode*& head, int data) {
if (head == nullptr) {
head = new BinaryTreeNode(data, nullptr, nullptr);
return;
}
if (data > head->data_) {
BST_Insert(head->r_, data);
}
else {
BST_Insert(head->l_, data);
}
}
BinaryTreeNode* BST::BST_Search(BinaryTreeNode* root, int key) {
if (root == nullptr || root->data_ == key)
return root;
if (key > root->data_)
return BST_Search(root->r_, key);
return BST_Search(root->l_, key);
}