Easy to understand C++ recursive


  • 0
    O
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            if (root == NULL) return -1;
            int min = INT_MAX; 
            int secMin = INT_MAX;
            findSecondMinimumValueHelper(root, min, secMin);
            return secMin == INT_MAX ? -1 : secMin;
        }
    
        void findSecondMinimumValueHelper(TreeNode* root, int& min, int& secMin)
        {
            if (root == NULL) return;
            if (root->val < min)
            {
                secMin = min;
                min = root->val;
            }
            else if (root->val < secMin)
            {
                if (root->val != min) secMin = root->val;
            }
            findSecondMinimumValueHelper(root->left, min, secMin);
            findSecondMinimumValueHelper(root->right, min, secMin);
        }
    };
    

Log in to reply
 

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