Java, O(1) space & one function solution


  • 0
    J
    int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
    
    public int findSecondMinimumValue(TreeNode root) {
        if (root == null){
            return -1;
        }
        first = Math.min(first, root.val);
        if (root.val > first && root.val < second){
            second = root.val;
        }
        findSecondMinimumValue(root.left);
        findSecondMinimumValue(root.right);
        return second == Integer.MAX_VALUE ? -1 : second;
    }

Log in to reply
 

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