Different Initial Setting in Java and in C++: null v.s. -1 (Why?)


  • 0
    C

    I am trying to convert the in-order traversal Java solution to C++. However, the code below in C++ does not work for the last testcase [0,null,2236,1277,2776,519] where its output is 540 not 519.

    class Solution {
    public:
        
        int minValue = INT_MAX;
        int prev = NULL;
        
        int getMinimumDifference(TreeNode* root) {
            if(root == NULL) return minValue;
            
            getMinimumDifference(root->left);
            if(prev != NULL){
                minValue = min(minValue, (root->val) - prev); 
            }
            prev = root->val;
            
            getMinimumDifference(root->right);
            
            return minValue;
        }
    };
    

    This code works after changing the initial value of prev from NULL to -1. I notice that in Java, I have to use Integer class instead of int. And the initial setting Integer prev = null works fine with all testcases in Java. Can anyone explain this difference? Thanks a lot!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.