Here is my insert method:
void BST::insert(Node* cur, int x) { //private method
if (!cur) {
cur = new Node(x);
}
else {
if (x < cur->val) {
if (cur->left) {
insert(cur->left, x);
}
else {
cur->left = new Node(x);
}
}
else if (x > cur->val) {
if (cur->right) {
insert(cur->right, x);
}
else {
cur->right = new Node(x);
}
}
}
}
void BST::insert(int x) { //public method
insert(root, x); //root is the root of the tree (private variable)
}
It works if my root pointer is not NULL. However, if the root is NULL, it doesn't construct into a Node pointer. Since pointers pass by reference, shouldn't it save outside of the function scope? Thanks