0

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?

  • 1
    In case it isn't clear from the duplicate, what happens is that the pointer is passed by value. So any change you make to the pointer is unseen by the caller (e.g. `nodePtr = CreateLeaf(num);`) Changes to the object the pointer points to are a different matter (e.g. `nodePtr->right = CreateLeaf(num);`) – juanchopanza Aug 10 '17 at 22:04
  • 1
    Yes that helped me understand it better. Thank you! – Elijah Hampton Aug 11 '17 at 01:27

0 Answers0