Search code examples
c++binary-treenodes

Can not delete a leaf from binary search tree


I have made a delete_node() function of a leaf from a binary search tree BST. Here is the behavior of delete_node() function:

  1. If the binary search tree was empty, it will inform you that the it is empty.
  2. Else if, that leaf has no child, so no further delegation is required. So, the pointer that points to that leaf is deleted then make it points to null. But the program unfortunately crashed.
    Here is the delete_node() function:

    void  BinarySearchTree :: delete_node(float deleted_key)
    {
      Node* deleted_node_address = return_node_address(deleted_key);
    
      if(root == NULL) cout<<"The tree is empty, No thing to delete\n";
    
      else if(deleted_node_address->left_ptr==NULL  &&  deleted_node_address->right_ptr==NULL)
      {
        cout<<"The element has no children, No linking required\n";
        delete deleted_node_address;
        deleted_node_address = NULL;
      }
    }
    

Here is the return_node_address function:

Node* BinarySearchTree  ::return_node_address(float req_key,Node *traverse_ptr)
{
    if(traverse_ptr==NULL)
    {
        cout<<"There is no data to return its addres";
        return NULL;
    }
    else if(traverse_ptr->key  ==  req_key)
    {
        return traverse_ptr;
    }
    else if(req_key  <  traverse_ptr->key  && traverse_ptr->left_ptr != NULL)
    {
        return_node_address(req_key, traverse_ptr->left_ptr );
    }
    else if(req_key  >  traverse_ptr->key  && traverse_ptr->right_ptr!= NULL)
    {
        return_node_address(req_key, traverse_ptr->right_ptr);
    }
    else
    {
        cout<<"The Key You Entred Is Not Found in The Tree";
        return NULL;
    }

}

Solution

  • The assignment

    deleted_node_address=NULL;
    

    clears the deleted_node_address variable, which is local to the BinarySearchTree :: delete_node(float deleted_key) function, but it does not clear the pointer to the deleted node from its parent node.

    As a result you made your tree invalid: it remained with some left_ptr or some right_ptr being not-NULL but pointing to a non-object. Hence a possible crash on the next attempt to access the pointed unused memory.

    Additionally, you call return_node_address() function to search a node to delete before you test for root==NULL. Are you sure that return_node_address method is NULL-root-proof...?