简体   繁体   中英

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: 图片

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

Thanks for your guides!

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM