I'm solving LeetCode 783. Minimum Distance Between BST Nodes and I've noticed that the difference between a correct solution and an incorrect solution is a reference (&
) at my function call, as follows:
Correct Solution:
class Solution {
public:
void traverse(TreeNode* root, TreeNode* &curr, int &sol){
if (root == nullptr) return;
traverse(root->left, curr, sol);
if(curr) sol = min(sol, abs(root->val - curr->val));
curr = root;
traverse(root->right, curr, sol);
}
int minDiffInBST(TreeNode* root) {
int sol = INT_MAX;
TreeNode* curr = nullptr;
traverse(root, curr, sol);
return sol;
}
};
Incorrect Solution:
class Solution {
public:
void traverse(TreeNode* root, TreeNode* curr, int &sol){
//Exactly the same as above!
};
As a student, this is the first time I have encountered this case related to Pointers and References. I'll appreciate any explanation of this difference.
CodePudding user response:
If you do this
void foo(int * inner_ptr) {
ptr ;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int outer_ptr = &arr[1];
foo(outer_ptr);
}
the outer_ptr
will still be equal to &arr[1]
.
You only changed the inner_ptr
, the copy of the outer_ptr
.
You can change the thing it points to.
void foo(int * inner_ptr) {
(*ptr) = 42;
}
But not the outer_ptr
itself
Therefore you need either this signature: (with reference)
void foo(int * & inner_ptr);
or this signature: (pointer to pointer) (in this case you would work with it differently in the function body tho)
void foo(int * * inner_ptr);
CodePudding user response:
The answer is that without reference (void traverse(TreeNode* root, TreeNode* curr, int &sol){...}
) curr
value will not be updated for the future calls of the function (which will be executed from the call-stack).
But when there is a reference (void traverse(TreeNode* root, TreeNode* &curr, int &sol){...}
) curr
value will be updated and will be used for the next calls until termination of the program.