c++从BST中删除节点
C++ delete a node from BST
我的删除功能有问题。我不知道是什么问题。请帮我解决这个问题。非常感谢。
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,像这个:
二叉搜索树实现
相关文章:
- 为什么我的删除节点函数实际上没有删除节点?
- 为什么"delete"关键字不删除节点?
- 以递归方式从链表中删除节点
- 根据 Pugixml 中的子值删除节点
- 基于给定字符串数据类型的链表删除节点
- 在双向链表中给定节点之后删除节点
- 如何在单链列表 c++ 中正确删除节点
- 在BST堆中删除节点免错误
- 为什么我的打印功能之一删除节点
- 重载运算符>>从二叉树中删除节点
- 删除节点方法实际上不会删除二叉搜索树中的节点.C++
- C bST删除节点会破坏排序算法
- 删除节点并处理新的 nullptr 和链接节点
- 如何从链表中删除节点
- 如何在用于删除节点的函数中检查我的链表是否C++为空
- 从BST删除节点时出错
- 二叉树,从树中删除节点后将其删除
- 链接列表删除节点C
- 在二进制搜索树中删除节点
- 使用类从双向链表中删除节点