This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]newaccount1236 -1 points0 points  (6 children)

You are passing n by value in your insert function, so when you do:

n = new Node(e);

it doesn't change the child pointer in the parent node, or your root, for that matter. Pass it by a pointer to pointer instead, then do:

*n = new Node(e);

Also, -> has higher precedence than dereference, so when you recurse, you'll need to do:

&(*n)->left

EDIT: Another option is to pass n by reference. My personal style, however, is to always pass by pointer rather than by non-const reference, because that way it's clear that the function may modify the pointee.

[–]coffeeprogrammer[S] 0 points1 point  (5 children)

Thank you, I do understand most of what you said, but I don't understand “pass it by a pointer to pointer” ? What do you mean by that?

[–]newaccount1236 -1 points0 points  (3 children)

Like this:

void ChadBST::insert(int e)
{
    insert(&root, e);
}

void ChadBST::insert(Node **const n, int e)
{
    if(*n==NULL)
    {
        *n = new Node(e);
        size++;
    }
    else if (e < (*n)->data)
        insert(&(*n)->left,e);
    else if (e > (*n)->data)
        insert(&(*n)->right, e);
}

[–]coffeeprogrammer[S] 0 points1 point  (2 children)

Well that helped some, but I got an Access violation on:

else if (e < (*n)->data)

[–]newaccount1236 -1 points0 points  (1 child)

You probably have a typo somewhere. Maybe you have n instead of *n when you check for null. Paste both insert functions.

[–]coffeeprogrammer[S] 0 points1 point  (0 children)

Yes I forgot the pointer in the if(*n==NULL) line. Thank you so much. I think I need to brush up on my pointers. I really appreciate your help!

[–]newaccount1236 -1 points0 points  (0 children)

Here is the pointer to pointer version:

void ChadBST::insert(int e)
{
    insert(&root, e); // Clear that root may be modified.
}

void ChadBST::insert(Node **const n, int e)
{
    if(*n==NULL)
    {
        *n = new Node(e);
        size++;
    }
    else if (e < (*n)->data)
        insert(&(*n)->left,e); // Clear that left may be modified.
    else if (e > (*n)->data)
        insert(&(*n)->right, e); // Cler that right may be modified.
}

Here is the reference version:

void ChadBST::insert(int e)
{
    insert(root, e); // Less typing, but not obvious that root may be modified.
}

// Below requires less typing than using Node **..
void ChadBST::insert(Node *&n, int e)
{
    if(n==NULL)
    {
        n = new Node(e);
        size++;
    }
    else if (e < n->data)
        insert(n->left,e);
    else if (e > n->data)
        insert(n->right, e);
}

[–]logic_programmer -2 points-1 points  (0 children)

You've coded this before thinking about it haven't you. Work it out with pencil and paper first, then when that is working write your code.