簡體   English   中英

在C ++中刪除二進制搜索樹的節點的實現問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM