gpt4 book ai didi

c++ - 我的红黑树析构函数有什么问题?

转载 作者:行者123 更新时间:2023-11-30 04:20:02 25 4
gpt4 key购买 nike

我正在构建一个红黑树,但我的类 RBTree 的析构函数可能存在一些问题。我给树添加了 10^7 的值,然后调用了析构函数,但是内存似乎没有被释放。 (我查看系统监视器,我的程序仍然使用 200MB)。

你能告诉我我的析构函数有什么问题吗?这是我的源代码。

抱歉我的英语不好。

#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;

enum Color {RED, BLACK};

template<class Data> class RBNode;
template<class Data> class RBTree;

template<class Data> class RBNode {
Color color; RBNode *p, *left, *right;
public:
Data v;
RBNode(Color color, RBNode *p, RBNode *left, RBNode *right, Data v):
color(color), p(p), left(left), right(right), v(v) {}
RBNode() {}
friend class RBTree<Data>;
};

template<class Data> class RBTree {
typedef RBNode<Data> Node;
typedef Node * PNode;
PNode root, nil;

void LeftRotate(PNode x) {
PNode y = x->right; x->right = y->left;
if(y->left != nil) y->left->p = x;
y->p = x->p;
if(x->p == nil) root = y;
else if(x == x->p->left) x->p->left = y;
else x->p->right = y;
y->left = x; x->p = y;
}

void RightRotate(PNode y) {
PNode x = y->left; y->left = x->right;
if(x->right != nil) x->right->p = y;
x->p = y->p;
if(y->p == nil) root = x;
else if(y == y->p->left) y->p->left = x;
else y->p->right = x;
x->right = y; y->p = x;
}

void insertFixUp(PNode z) {
while(z->p->color == RED) {
if(z->p == z->p->p->left) {
PNode y = z->p->p->right;
if(y->color == RED) z->p->color = y->color = BLACK, z->p->p->color = RED, z = z->p->p;
else {
if(z == z->p->right) LeftRotate(z = z->p);
z->p->color = BLACK; z->p->p->color = RED; RightRotate(z->p->p);
}
} else {
PNode y = z->p->p->left;
if(y->color == RED) z->p->color = y->color = BLACK, z->p->p->color = RED, z = z->p->p;
else {
if(z == z->p->left) RightRotate(z = z->p);
z->p->color = BLACK; z->p->p->color = RED; LeftRotate(z->p->p);
}
}
}
root->color = BLACK;
}

public:
RBTree() {
nil = new Node;
nil->color = BLACK;
nil->p = nil->left = nil->right = nil;
nil->v = Data();
root = nil;
}

~RBTree() {
delete root;
delete nil;
}

void insert(Data v) {
PNode y = nil, x = root;
while(x != nil) {
y = x;
x = v < x->v ? x->left : x->right;
}
PNode z = new Node; *z = Node(RED, y, nil, nil, v);
if(y == nil) root = z;
else if(v < y->v) y->left = z;
else y->right = z;
insertFixUp(z);
}
};

int main() {
RBTree<int> tree;
for(int i = 0; i < 10000000; ++i) tree.insert(i);
tree.~RBTree();
getchar();
return 0;
}

最佳答案

您需要向您的 RBNode 添加一个析构函数,它会删除它的子节点:

template<class Data> class RBNode {
...
~RBNode() {
delete left;
delete right;
}
...
};

照原样,您将在删除树时删除根节点,但根节点本身不会释放其资源。因此,您丢失了对根的子节点及其所有子节点等的所有引用。因为您不再拥有对这些节点的引用,所以无法删除它们,存在内存泄漏。

析构函数确保当我们即将失去对节点子节点的引用时,这些子节点(以及它们的子节点等等)将被释放。

关于c++ - 我的红黑树析构函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435603/

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