This is my function to insert a node into a BST. This version works, but originally I was passing the struct (TreeNode) into the function only using a pointer. (*) See below.
void insert(TreeNode *& nodePtr, int num) {
if (nodePtr == NULL) {
nodePtr = CreateLeaf(num);
}
else if (num < nodePtr->data) {
if (nodePtr->left != NULL) {
insert(nodePtr->left, num);
}
else {
nodePtr->left = CreateLeaf(num);
}
}
else if (num > nodePtr->data) {
if (nodePtr->right != NULL) {
insert(nodePtr->right, num);
}
else {
nodePtr->right = CreateLeaf(num);
}
}
}
Original:
void insert(TreeNode * nodePtr, int num)
I thought by using, *, I was passing the address of the variable to the function. Without the ampersand the TreeNode pointer stayed NULL instead of linking the nodes. Can someone clarify this for me?