C++ DFS solution, NO auxiliary function


  • 0
    P
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            if (root==NULL || root->left == NULL) return -1;
            
            int l_min2, r_min2;
            // find second minimum value from left subtree
            if (root->val == root->left->val)
                l_min2 = findSecondMinimumValue(root->left);
            else l_min2 = root->left->val;
            
            // ... right subtree
            if (root->val == root->right->val)
                r_min2 = findSecondMinimumValue(root->right);
            else r_min2 = root->right->val;
            
            if (l_min2 == -1) return r_min2;
            if (r_min2 == -1) return l_min2;
            return min(l_min2, r_min2);
        }
    };
    

Log in to reply
 

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