Em thực hiện cách thức xóa 1 node trong BST bằng cách gọi hàm recursive_Delete.
Code:
void removeNode(TreeNode *&subroot, int target) {
TreeNode *pDel = subroot;
if (subroot->left == NULL)
{
subroot = subroot->right;
}
else if (subroot->right == NULL)
{
subroot = subroot->left;
}
else
{
TreeNode *parent = pDel;
pDel = pDel ->left;
while (pDel->right != NULL)
{
parent = pDel;
pDel = pDel->right;
}
subroot->data = pDel->data;
if (parent == subroot)
{
parent->left = pDel->left;
}
else
{
parent->right = pDel->left;
}
delete pDel;
}
return;
}
void recursive_Delete(TreeNode *&subroot, int target) {
if (subroot == NULL)
return ;
else if (target < subroot->key)
{
return recursive_Delete(subroot->left, target);
}
else if (target > subroot->key)
{
return recursive_Delete(subroot->right, target);
}
else
{
removeNode(subroot, target);
}
}
Em thấy hàm đệ quy ở trên chỉ có nhiệm vụ là tìm đúng node cần xóa để gọi hàm removeNode, còn việc xóa node là do hàm removeNode thực hiện. Vì vậy khi em thử chạy trực tiếp hàm removeNode cho node cần xóa nhưng lại không thể xóa được (trường hợp cụ thể là node lá), mấy bác có thể giải thích giúp em tại sao được không ạ ?