0
我正在製作二叉搜索樹的析構函數。我用第一個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
}
[MCVE]請像往常一樣。 –