gpt4 book ai didi

c++ - 二叉搜索树的析构函数

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

我正在为二叉搜索树创建一个析构函数。我用第一个 while 循环遇到了无限循环,因为当 kill 设置为 NULL 时,head 的左指针永远不会设置为 NULL。为什么会这样,我该如何解决?

提前致谢!

BST::~BST()
{
Node* kill = head;
/*
While-loop runs until all of head's left branch has been deleted
*/
while(head->get_left() != NULL)
{

kill = head->get_left();//Set the pointer variable kill to heads left node.

/*
While-loop moves the kill pointer to a bottom node with that has no children
*/
while(kill->get_left() != NULL && kill->get_right() != NULL)
{
if(kill->get_left() != NULL)
{
kill = kill->get_left();
}
if(kill->get_right() != NULL)
{
kill = kill->get_right();
}
}

delete kill;//deletes the bottom node with no children
kill = NULL;
}

kill = head;
/*
While-loop runs until all of head's right branch has been deleted
*/
while(head->get_right() != NULL)
{

kill = head->get_right();//Sets the kill pointer to head's right node

/*
While-loop moves the kill pointer to a bottom node with no children
*/
while(kill->get_left() != NULL && kill->get_right() != NULL)
{
if(kill->get_left() != NULL)
{
kill = kill->get_left();
}
if(kill->get_right() != NULL)
{
kill = kill->get_right();
}
}

delete kill;//deletes the bottom node with no children
kill = NULL;


}

delete kill;//deletes the head node



}

最佳答案

看起来你可以简化你的析构函数。为 Node 实现析构函数。像这样:

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

在这种情况下,您的 BST::~BST() 将是:

BST::~BST()
{
delete head;
head = NULL;
}

关于c++ - 二叉搜索树的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38709135/

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