简体   繁体   English

在C ++中删除二进制搜索树的节点的实现问题

[英]Implementation issue in deleting the node of a binary search tree in c++

I have implemented delete method for a Binary Search Tree by referring the pseudo code from CLRS. 我已经通过引用来自CLRS的伪代码为二进制搜索树实现了删除方法。 Below is the buggy implementation. 下面是越野车的实现。 Initially when I delete the leaf node it works but when I am deleting the root node the code fails. 最初,当我删除叶节点时,它可以工作,但是当我删除根节点时,代码将失败。 Specifically - Value of new root node is coming in the transplant method but in the delete_node method it again shows old node value. 具体来说,新的根节点的值将在移植方法中出现,但在delete_node方法中,它将再次显示旧的节点值。 Could someone please point out the error. 有人可以指出错误。 Thanks in advance. 提前致谢。

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;
            }
        }
};

I think you a missing a while loop or an iterator to traverse through the binary tree. 我认为您缺少while循环或迭代器来遍历二叉树。 This will look up for the node that needs to be deleted and then delete it regardless of its current position. 这将查找需要删除的节点,然后不管其当前位置如何将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM