0

我通过引用 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;
            }
        }
};
4

1 回答 1

0

我认为您缺少一个 while 循环或遍历二叉树的迭代器。这将查找需要删除的节点,然后无论其当前位置如何都将其删除。

于 2013-07-22T18:06:35.910 回答