Java simple recursive method with one global variable


  • 0
    class Solution {
        private int minValue = -1;
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null) return -1;
            if (minValue != -1 && root.val != minValue)
                return root.val;
            minValue = root.val;
            
            if (root.left == null || root.right == null) return -1;
            int r1 = findSecondMinimumValue(root.left);
            int r2 = findSecondMinimumValue(root.right);
            if (r1 == -1 && r2 == -1) 
                return -1;
            else if (r1 == -1) 
                return r2;
            else if (r2 == -1)
                return r1;
            else 
                return Math.min(r1, r2);
        }
    }
    

Log in to reply
 

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