Binary Search Tree Insert Method Error

EDIT: I've come across an error. Once i insert the new node into the tree and use a search function to see if it has been inserted it works and then my insert function ends. However when i check in main to see if i still have that node attached no node is attached. It simply says theres no list.


EDIT::Removed some code
Last edited on
Line 3: on every call of this function you do look at the root rather than r.

Line 11: overwrites the root, rather than creates a new leaf.


PS. You could create a constructor for the Node.
A new Node( n, p ); looks more clear (in the insert) than the current 5-liner.
Is it my insert function failing? Or is it my find function failing? Any help would be appreciated. I'm not sure what happen to my last response. It appears only the very last insert works and makes root point to it but i cant figure out why
Last edited on
The private insert function is modifying the root here:
1
2
        r = r->right;
        insert(r, n, p);
and here
1
2
        r = r->left;
        insert(r, n, p);


You could try simply
 
        insert(r->right, n, p);
and
 
        insert(r->left, n, p);
It worked! Why is that though? Isnt it still passing in the same thing except in the function call instead of prior to it?
Isnt it still passing in the same thing except in the function call instead of prior to it?

It passes a different variable.

Note that Node*& r is passing the pointer by reference, so that the original value is changed.
void Tree::insert(Node*& r, std::string n, std::string p)


r = r->right; will modify the pointer r, which is originally the root variable passed on the first call.
insert(root, n, p);
Ohhh That makes so much more sense. I see that now. Thank you for your help and clear explanation!!
Topic archived. No new replies allowed.