简体   繁体   中英

Deleting node from binary tree

A binary tree of abstract classes. I have three deleting methods, the first is for user menu, and others are recursive. I have a trouble with decrementing nodes' count after deleting one. Help please, where should I write "r->count--"?

Node* Del(Node *t, Node *t0) {
    if (t->left != nullptr) {
        t->left = Del(t->left, t0);
        return t;
    }
    t0->o = t->o;
    Node *x = t->right;
    delete t;
    return x;
}
Node* deleteNodes(Node *r, Node *elem, bool &deleted) {
    bool del;
    if (r == nullptr) {
        deleted = false;
        return r;
    } 
    if (equal(elem->o, r->o) < 0) {
        r->left = deleteNodes(r->left, elem, del);
        deleted = del;
        return r;
    }
    else if (equal(elem->o, r->o) > 0) {
        r->right = deleteNodes(r->right, elem, del);
        deleted = del;
        return r;
    }
    deleted = true;
    if (r->left == nullptr && r->right == nullptr) {
        delete r;
        return nullptr;
    }
    if (r->left == nullptr) {
        Node *x = r->right;
        delete r;
        return x;
    }
    if (r->right == nullptr) {
        Node *x = r->left;
        delete r;
        return x;
    }
    r->right = Del(r->right, r);
    return r;
}

You should place it in the code where you have found a node to delete. This is also where you set deleted to true :

So:

deleted = true;
r->count--;

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