我的删除功能有问题。我不知道这似乎是什么问题。请帮我解决这个问题。非常感谢你。
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;
}
答案 0 :(得分:3)
不幸的是,你在这里遇到了很多问题;我认为你误解了内存分配:
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)
逻辑需要凝聚 - 请查看有关SO BST
的一些帖子,如下所示: