二进制搜索树的析构函数

时间:2016-08-01 22:36:07

标签: 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() != 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



}

1 个答案:

答案 0 :(得分:2)

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

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

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

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