c++ - 如何为我的 AVL 树创建析构函数?

标签 c++ class tree destructor

我有代码:

class Node
{
public:
    ~Node();
    int key;
    Node *left;
    Node *right;
    int height;
};


Node::~Node()
{
    delete this->left;
    delete this->right;
    this->left = this->right = NULL;
}

我相信析构函数不能正常工作,如果不删除“根”,请帮助我如何完全删除我的树

最佳答案

您希望析构函数在您的 AVLtree 类中,而不是在您的 Node 类中。您应该考虑制作一个递归辅助函数来执行此操作,它将使用后序遍历来删除树。

希望对您有所帮助。这是一个非常基本的例子:

// you will not be needing a destructor for Node because it`s left and right pointers are always going to be nullptr when a Node gets created. You will only need a destructor for Node if you have another resource that you are allocating upon the creation of a Node by using the ```new``` keyword.
struct Node
{
    Node* left = nullptr;
    Node* right = nullptr;
};

class AVLtree
{
public:

    Node* root = nullptr;

    void clearTreeHelper(Node*& treeptr)
    {
        if (treeptr != nullptr)
        {
            clearTreeHelper(treeptr->left);
            clearTreeHelper(treeptr->right);
            delete treeptr;
            treeptr = nullptr;
        }
    }

    ~AVLtree()
    {
        clearTreeHelper(root);
        if (root == nullptr)
        {
            cout << "Root has been cleared!\n";
        }
    }
};

int main()
{
    {
        AVLtree a;
        a.root = new Node;
        a.root->left = new Node;
        a.root->right = new Node;
        a.root->right->left = new Node;
        a.root->right->right = new Node;
    }
}

关于c++ - 如何为我的 AVL 树创建析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59235628/

相关文章:

c++ - Qt 双击检查鼠标左键

c++ - 使用 2 个分隔符 '+' 和 '-"在 C++ 中拆分字符串

PHP静态函数在动态环境中调用

Java数据结构

jquery 文件树 - 默认打开的文件夹?

c++ - 通过placement-new手动构造一个平凡的基类

c++ - 尝试创建一个程序来查找非二叉树的高度。以一个很长的循环结束,没有答案

c++ - 从 DLL 导出前向声明的类

c++ - 我的 c++ 类中产生的错误是什么?

java - B树实现