c++从BST中删除节点

C++ delete a node from BST

本文关键字:删除 节点 BST c++      更新时间:2023-10-16

我的删除功能有问题。我不知道是什么问题。请帮我解决这个问题。非常感谢。

node* tree_minimum(node *x){
    while(x->left!=NULL){
        x=x->left;
    }
    return x;
}
node* tree_successor(node *x){
    if(x->right!=NULL)
        return tree_minimum(x->right);
    node *y;
    y=new node;
    y=x->parent;
    while(y!=NULL&&x==y->right){
        x=y;
        y=y->parent;
    }
    return y;
}
node* tree_search(node* x,int k){
    if(x==NULL||k==x->key)
        return x;
    if(k<x->key)
        return tree_search(x->left,k);
    else
        return tree_search(x->right,k);
}
node* tree_delete(int b){
    node *y;
    y=new node;
    node *x;
    x=new node;
    node *z;
    z=new node;
    z=tree_search(root,b);
    if(isempty()){
        cout<<"TREE is empty.";
        return NULL;
    }
    if(z->left==NULL||z->right==NULL)
        y=z;
    else
        y=tree_successor(z);
    if(y->left!=NULL)
        x=y->left;
    else
        x=y->right;
    if(x!=NULL)
        x->parent=y->parent;
    if(y->parent==NULL)
        root=x;
    else{
    if(y=y->parent->left)
        y->parent->left=x;
    else
        y->parent->right=x;
    }
    if(y!=z)
        y->key=z->key;
    return y;
}

不幸的是,你在这里有很多问题;我想你误解了内存分配:

node *y;
y=new node;
y=x->parent;  // Holy Mackerel!

在第二行分配内存,返回一个地址给新分配的内存;下一行更改了y指向(!!)的地址——丢失了分配的内存位置并造成内存泄漏。由于这些代码分散在整个代码中,并且您没有main()或显示调用的代码-因此不太需要继续进行。

如果你只是复制指针,你不需要执行动态分配(即new操作符)。

int *x = new int;
int y = 2;
*x = 1;  // Assigns the memory (int) pointed to by x to 1
x = &y;  // Reassigns x to point to y - but without delete the allocated memory's last reference is lost

我建议你在继续阅读之前先读一本书。

编辑:还要注意条件,如:

if (y=y->parent->left)

当你最有可能的意思是:

if (y == y->parent->left)

逻辑需要压缩-检查一些关于BST的帖子在SO,像这个:

二叉搜索树实现