C++ 二叉搜索树的析构函数
我正在为二叉搜索树制作一个析构函数。我用第一个while循环命中了一个无限循环,因为当kill设置为NULL时,head的左指针永远不会设置为NULL。这是为什么?我如何修复它 提前谢谢C++ 二叉搜索树的析构函数,c++,binary-search-tree,destructor,C++,Binary Search Tree,Destructor,我正在为二叉搜索树制作一个析构函数。我用第一个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() != NUL
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()
{
delete left;
left = NULL;
delete right;
right = NULL;
}
在这种情况下,您的BST::~BST()
将是:
BST::~BST()
{
delete head;
head = NULL;
}
看起来你可以简化你的析构函数。为
节点
实现析构函数。大概是这样的:
Node::~Node()
{
delete left;
left = NULL;
delete right;
right = NULL;
}
在这种情况下,您的BST::~BST()
将是:
BST::~BST()
{
delete head;
head = NULL;
}
请像往常一样。请像往常一样。不需要影响
nullptr
。使用std::unique_ptr
甚至可以避免这种简化的代码。不需要影响nullptr
。使用std::unique_ptr
甚至可以避免这种简化的代码。