Buck Wheat
Buck Wheat

Reputation: 41

Destructor for Binary Search Tree

I am making a destructor for a binary search tree. I hit an infinite loop with the first while-loop because head's left pointer never gets set to NULL when kill is set to NULL. Why is this and how can I fix it?

Thanks in advance!

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



}

Upvotes: 0

Views: 695

Answers (1)

Nikita
Nikita

Reputation: 6427

Looks like you can simplify your destructor. Implement destructor for Node. Something like this:

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

In this case your BST::~BST() will be:

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

Upvotes: 2

Related Questions