Why is my node set as a nullptr after I have set it = new Node?

Viewed 130

I have initialized a node pointer as nullptr and passed it as reference into a helper function. Inside the helper function, I set the pointer which was previously nullptr equal to new Pointer. However, after the function ends, it is set to nullptr again.

void helper(vector<int>& nums, int start, int end, TreeNode* root){
    if(start >= end) return;
    root = new TreeNode;
    int median = (start + end) / 2;
    root -> val = nums[median];
    helper(nums, start, median - 1, root -> left);
    helper(nums, median + 1, end, root -> right);
}

TreeNode* sortedArrayToBST(vector<int>& nums) {
    TreeNode* root = nullptr;
    helper(nums, 0, nums.size() - 1, root);
    return root;
}
2 Answers

passed it as reference into a helper function

No, the pointer is passed by value itself. The parameter root is just a copy of the argument, any modification on the pointer itself inside the function has nothing to do with the argument.

Change it to pass-by-reference:

void helper(vector<int>& nums, int start, int end, TreeNode*& root){
//                                                          ^
    if(start >= end) return;
    root = new TreeNode;
    int median = (start + end) / 2;
    root -> val = nums[median];
    helper(nums, start, median - 1, root -> left);
    helper(nums, median + 1, end, root -> right);
}

Parameters are passed by value in C++. When you have

void foo(sometype x) {
    x = something;    // modifies the local x
}

Then the modification of x will only be visible inside the function, because it is made on the x local to the function. Pointers are no exception. If you want to modifiy the original argument you need to pass by reference:

void bar(sometype& x) {
    x = something;   // modifies the object refered to by x
}

TL;DR you need

void helper(vector<int>& nums, int start, int end, TreeNode*& root){
       ....

PS: I suppose your confusion stems from the fact that a pointer allows you to modify the pointee. A copy of a pointer points to the same object, hence...

void moo(int* x) {
    *x = 42;        // modifies the int pointed to by x
}

int a = 0;
int* p = &a;
moo(p);             // x above is a copy of p

Though, in general references should be prefered (unless nullptr is a valid argument). Moreover you want to modify the pointer not the pointee.

Related