简体   繁体   中英

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. 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. 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. This will look up for the node that needs to be deleted and then delete it regardless of its current position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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