user2611244
user2611244

Reputation: 51

recursively delete every nodes in binary tree

Following is my code to recursively delete every nodes in a Binary Search Tree:

template <class T>
bool BST<T>::clear()
{
    if(root == NULL)
    {
        cout << "Empty" << endl;
        return false;
    }
    else
    {
        clearNodes(root);
        return true;
    }

}

template <class T>
void BST<T>::clearNodes(BTNode<T> *cur)
{
    if(cur == NULL)
    {
        return;
    }

    clearNodes(cur->left);
    clearNodes(cur->right);

    delete cur;
}

In my main function, when I try to print out the content to check whether the nodes are deleted after running my clear function, somehow I encounter the weird display here: Image

May I know that is my nodes are actually deleted through the clear function above?

Thanks for your guides!

Upvotes: 0

Views: 5376

Answers (2)

UmNyobe
UmNyobe

Reputation: 22890

I assume "checking that the nodes are deleted" is equivalent to clear() printing empty. Your algorithm is missing the step where it reset the deleted node.

A modified version is

template <class T>
void BST<T>::clearNodes(BTNode<T>* &cur) //reference on pointer
{
  if (cur==NULL)
  {
    return;
  }

  clearNodes(cur->left);
  clearNodes(cur->right);

delete cur;
cur = NULL; //neccessary
}

Edit : Explanation about changes Once you observe the issue about the node not set to null, the first iteration will be to set the node in question after every call, ie

clearNodes(cur->right);
cur->right = NULL;

This give the responsibility to the caller, and his a potential defect because sooner or later the caller may forget to set to null or may set the wrong value. Thus you want to set in clearNodes.In order to modify a pointer inside the function you need to pass either a pointer to it or a reference. In c++, I prefer to pass a reference. Thus the signature become¨

void BST<T>::clearNodes(BTNode<T>* &cur);

Upvotes: 2

Haggai Magen
Haggai Magen

Reputation: 103

I guess that the root of the tree is not set to Null, therefor it holds garbage, and the print function is iterating a random-garbage tree. Make sure you set NULL to the tree root when the clear method ends.

template <class T>
bool BST<T>::clear()
{ 
   if (root==NULL)
  {
    cout << "Empty" << endl;
    return false;
  }

  else
  {
    clearNodes(root);
    root = NULL;
    return true;
  }     

}

I assume that when you print - you check if the tree root is null or not in order to determine whether the tree is empty or not.

Upvotes: 0

Related Questions