[英]Implementation issue in deleting the node of a binary search tree in c++
我已经通过引用来自CLRS的伪代码为二进制搜索树实现了删除方法。 下面是越野车的实现。 最初,当我删除叶节点时,它可以工作,但是当我删除根节点时,代码将失败。 具体来说,新的根节点的值将在移植方法中出现,但在delete_node方法中,它将再次显示旧的节点值。 有人可以指出错误。 提前致谢。
class bst {
public:
struct node
{
int data;
struct node* ltson;
struct node* rtson;
struct node* parent;
}*btroot;
// replaces the subtree rooted at node u with the subtree rooted at node v
void transplant(bst T, struct node* u, struct node *v) {
if(u->parent==NULL){
T.btroot = v;
}
else if(u->parent->ltson == u)
u->parent->ltson = v;
else
u->parent->rtson = v;
if(v!=NULL)
v->parent = u->parent;
}
void delete_node(bst T,struct node* z) {
struct node * y;
if(z->ltson==NULL)
transplant(T,z,z->rtson);
else if(z->rtson==NULL)
transplant(T,z,z->ltson);
else {
y = minimum(z->rtson);
if(y->parent!=z) {
transplant(T,y,y->rtson);
y->rtson = z->rtson;
y->rtson->parent = y;
}
transplant(T,z,y);
cout<< (T.btroot->data)<<endl; //Old value of root is being printed
y->ltson = z->ltson;
y->ltson->parent = y;
}
}
};
我认为您缺少while循环或迭代器来遍历二叉树。 这将查找需要删除的节点,然后不管其当前位置如何将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.