I am having trouble with the following code. I am a java developer trying to teach myself c++. Mainly my code in main() is not inserting anything to the root Node. Can anyone help me. I am sure there is something off with my pointers.
class Node{
public:
Node* left;
Node* right;
int data;
Node(int n){
data = n;
right = NULL;
left = NULL;
}
};
class BST{
Node* root;
public:
BST(){
root = NULL;
}
void insert(int e){
pinsert(root, e);
}
void pinsert(Node* sr, int e){
if(sr == NULL){
sr = new Node(e);
}
else{
if((sr->data) > e ){
pinsert(sr->left, e);
}
else{
pinsert(sr->right, e);
}
}
}
};
int main(){
BST tree;
tree.insert(6);
tree.insert(7);
}
The problem with your insert is when you begin with an empty list. When you pass a
Node *to yourpinsertfunction, the argument is passed by value, so your function ends up with a copy of the pointer. When the pointer isNULL, you change the pointer to point to your new node. Since you only have a copy of the pointer inpinsert, this only changes the copy of the pointer. When the function returns, the pointer, and the list, is unchanged.Pass a reference to the pointer to get around this:
Now the rest of your code doesn’t need to change, and your function can change the pointer.
This problem is analogous to passing object references in java: you can change the contents of the object, by setting fields and calling methods, but you can’t change the argument to a new object, or to
null.