简体   繁体   English

销毁二叉树中的节点

[英]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:我使用new创建节点,但现在我想在析构函数中删除它们:

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?有没有办法只在析构函数中使用whilefor循环,而不是在析构函数中递归调用方法? 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?为什么需要递归 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. dtor 将通过所有节点调用整个树。

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).如果您的树节点存储它们的父节点,则可以从任何 position 中找到以下节点,并且您可以对其进行 while 循环,但这将比递归形式花费更多时间(因为对 next() 的调用将需要的不仅仅是单个节点步骤的一半时间,递归下降永远不会花费超过一个步骤来找到下一个要释放的节点)。

You can breadth-delete a tree with a std::queue .您可以使用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.这样做会调用双重删除和大量未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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