简体   繁体   中英

Binary tree Node pointers

I have a struct for my binary tree

struct BST::Node
{
Key key;
Item item;

Node* leftChild;
Node* rightChild;

Node(Key k, Item i)
{
    key = k;
    item = i;

    leftChild = nullptr;
    rightChild = nullptr;

}
};

I am trying to insert into the tree however I am getting an error saying if there is a handler for this exception the program may be safely continued. I think there might be something wrong with the way I am using pointers but I'm not 100% sure what it is, any help would be appreciated, thanks. This is my insert method that has to use recursion

void BST::insert(Key k, Item i)
{
    insertRec(k, i, root);
}

void BST::insertRec(Key k, Item i, Node* n)
{
    if (n == NULL)
    {
        n->item = i;
        n->key = k;
    }
    else if (k < n->key)
    {
        insertRec(k, i, n->leftChild);
    }
    else if (k > n->key)
    {
        insertRec(k, i, n->rightChild);
    }   
} 

Node* root is a nullptr.

Look closely at the following snippet from your code:

void BST::insertRec(Key k, Item i, Node* n)
{
    if (n == NULL)
    {
        n->item = i;
        n->key = k;
    }

You are setting n->item = i when n == NULL . This is wrong! NULL pointers don't point at valid objects.

Instead, you should just allocate a new node:

if (n == NULL)
{
    n = new Node(k, i);
}

But remember, when you are removing a node from your tree, after returning the value, you should always delete it.

Moreover , you should allocate your root during the construction of you BST class using the same method, and delete it during destruction.

Few things you need to take care: 1) inside

if (n == NULL)
{
    n->item = i;
    n->key = k;
}

above block before assigning item and key values, you need to allocate memory to the node.

n = new Node(i,k);

2) Now even after following the first point mentioned above the new node created will not be assigned to the root of BST(if tree is empty) as the root is passed by value. So either pass root as reference or as a pointer to pointer. Change the new node creation part as per your decision to pass by reference or by pointer to pointer.

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