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.