1
我试图实现一个二叉搜索树,并且我有一个节点删除问题。我做了一些测试,我认为我的功能唯一的问题是这种情况下,要删除的节点有两个孩子。我似乎在参考文献中的某处出现了混乱。这似乎是一个简单的问题,但我一直试图自己修复它太久在BST中删除一个带有两个子节点的节点
struct node
{
int val;
struct node *l;
struct node *r;
}*Head=NULL;
void del_x(struct node *&k,int x)
{
struct node *tmp,*tmp2,*rem;
if (k==NULL) return;
if (x > k->val) {if(k->r==NULL)return;else del_x(k->r,x);}
if (x < k->val) {if(k->l==NULL)return;else del_x(k->l,x);}
if (x == k->val)
{
tmp=k;
if (k->l==NULL && k->r==NULL) {tmp=k->l;k=tmp;delete tmp;return;}//no children
else if (k->l==NULL) {tmp=k->r;k=tmp;return;}//one child on the left
else if (k->r==NULL) {tmp=k->l;k=tmp;return;}//one child on the right
else //two children <-I think the problem lies in this else
{
rem=k;
tmp=k->r; //go to right subtree
while(tmp->l!=NULL) {tmp2=tmp;tmp=tmp->l;} //search minimum
tmp2->l=NULL;
k=tmp;
rem->val=tmp->val;
k=rem;
return;
}
}
}
非常感谢:)我刚刚遇到了一个问题,当我写“删除k;”时在“if(x == k-> val)”的末尾,它将左边的孩子设置为0,但没有它,该功能工作得很好。 – vois
对不起!我的错:应该删除tmp! – Christophe