gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:02:46 24 4
gpt4 key购买 nike

我有代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com