Saturday, 15 April 2017

Deleting empty Child node with causing seg fault

The purpose of the code is to insert a new node into a binary tree, but rather then the left root or right root in the tree be set to Null it is the left and right roots are pointing to empty nodes. So when inserting a new normal node into the tree there is a old empty node in hanging out. How would I be able to delete this empty node? I need to be able to delete this empty node, because when I run my clear a seg fault is caused

// insert in a normal_node
    //   Postcondition: Returns a pointer to this node.
    //
    //   Implementation note:
    //     - If this node is holding the value `k`, insert does nothing but
    //       return the `this` pointer.
    //     - Otherwise, depending on how the value `k` compares with the data
    //       in this node, insert makes a recursive call to insert `k` on either
    //       the left- or right-subtree of this node (and returns the `this`
    //       pointer).
    node * normal_node::insert(int k)
    {
        if (this -> getData() == k)
        {
            return this;
        }
        if (k > this -> getData())
        {
            right = getRight() -> insert(k);
            return this;

        }
        else
        {
            left = getLeft() -> insert(k);
            return this;
        }

}
// clear
//   Deletes all the descendants of this node.
//   Postcondition: This node is a leaf.
//   Implementation note:  Use recursive divide-and-conquer.
void normal_node::clear()
{
    if (!this -> isLeaf())
    {
        this -> getRight() -> clear();
        this -> getLeft() -> clear();
        if (this -> getRight() != this || this -> getLeft() != this)
        {
            delete this -> getLeft();
            delete this -> getRight();
        }

    }
}



via Terriyon Veasy

No comments:

Post a Comment