share my java solution.


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int findSecondMinimumValue(TreeNode root) {
            if(root==null || (root.left==null && root.right==null)){
                return -1;
            }
            
            return findNextLarger(root);
        }
        
        public int findNextLarger(TreeNode root){
            if(root.left==null&&root.right==null){
                return -1;
            }
            
            int ans=-1;
            int left = findNextLarger(root.left);
            int right = findNextLarger(root.right);
            
            if(root.left.val==root.val&&root.right.val==root.val){
                if(left==-1&&right==-1){
                    return -1;
                }else if(left!=-1&&right!=-1){
                    ans = Math.min(left,right);
                }else{
                    ans = left==-1?right:left;
                }
                
                return ans;
                
            }else{
                ans = Math.max(root.left.val,root.right.val);
            }
            
            if(left!=-1){
                ans = Math.min(left,ans);
            }
            if(right!=-1){
                ans=Math.min(ans,right);
            }
            
            return ans;
        }
    }
    
    

Log in to reply
 

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