Easy to read Java Solution


  • 0
    K
    class Solution {
        public int findSecondMinimumValue(TreeNode root) {
            //We need to find something more than root.val
            int ans = find(root, root.val);
            if(root.val == ans) return -1;
            else return ans;
        }
        
        private int find(TreeNode root, int val){
            if(root.val > val) return root.val; 
            if(root.left == null) return root.val; //node has two or no child
            
            int left = find(root.left, val);
            int right = find(root.right, val);
            
            //Now we have three numbers left, right and value of current node
            //The fact we have a left and right means that node value is same as val
            int small = Math.min(left, right);
            int large = Math.max(left, right);
            
            if(small == root.val) return large;
            else return small;
        }
    }
    

Log in to reply
 

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