简体   繁体   中英

Destroying nodes in a binary tree

Suppose I have a certain binary tree. I used new to create nodes, but now I want to delete them in the destructor:

void BinaryTree::recursiveDestructor(Node *& noeud){
    if (node != 0) {
        recursiveDestrutor(node->leftTree);
        recursiveDestructor(node->rightTree);
        delete node;
        node = 0;
    }
}

And I use the method in the destructor

BinaryTree::~BinaryTree(){
    recursiveDestructor(root);
}

Is there a way to just use a while or a for loop in the destructor instead of calling recursively a method inside the destructor? It would be faster using a loop and avoid using a method inside the destructor. If I can't use a loop, is there a way to improve the performance?

Why do you need a recursive dtor? Just do

Node::~Node()
{
   delete left;  // assuming left and right are both an instance of Node
   delete right;
}

BinaryTree::~BinaryTree() {
   delete root;
}

The dtor will be called down the whole tree working through all the nodes.

If your tree nodes store their parent it is possible to find the following node from any position and you could do a while loop on that but it will take more time than the recursive form (because the call to next() will require more than just a single node step half the time where the recursive-descent never takes more than a single step to find the next node to free).

You can breadth-delete a tree with a std::queue . Note: this is hammered out online with no syntax checking, but hopefully you get the idea:

BinaryTree::~BinaryTree()
{
    if (!root)
        return;

    std::queue<Node*> q;
    q.push(root);
    while (!q.empty())
    {
        Node *p = q.front();
        q.pop();
        if (p->left)
            q.push(p->left);
        if (p->right)
            q.push(p->right);
        delete p;
    }
}

Note: it is imperative that the nodes are not child-lifetime managed. Ie a node cannot auto-delete it's children on destruction. Doing so would invoke a double-delete and a boatload of undefined behavior.

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