Search code examples
c++pointersrecursiontreenodes

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


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;
}

Solution

  • 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);
    }