My Java solution with clear explanation


  • 0
    W
    
    /**
     * 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) return -1;
            else {
                if(root.left == null) return -1;
                else {
                    if(root.left.val != root.val && root.right.val != root.val) {
                        return Math.min(root.left.val, root.right.val); //both left and right child do not equal to root
                    }
                    else if(root.left.val != root.val && root.right.val == root.val) {
                        if(findSecondMinimumValue(root.right) == -1) return root.left.val; // right subtree has no second minimum and left child does not equal to root
                        else return Math.min(root.left.val, findSecondMinimumValue(root.right)); // right subtree has second minimum and left child does not equal to root
                    }
                    else if(root.left.val == root.val && root.right.val != root.val) {
                        if(findSecondMinimumValue(root.left) == -1) return root.right.val; // left subtree has no second minimum and right child does not equal to root
                        else return Math.min(findSecondMinimumValue(root.left), root.right.val); // left subtree has second minimum and right child does not equal to root
                    }
                    else { //both left and right child equal to root
                        if(findSecondMinimumValue(root.left) == -1) return findSecondMinimumValue(root.right); // left subtree has no minimum
                        else if(findSecondMinimumValue(root.right) == -1) return findSecondMinimumValue(root.left); // right subtree has minimum
                        else return Math.min(findSecondMinimumValue(root.left), findSecondMinimumValue(root.right)); // both left and right subtrees have minimum
                    }
                }
            }
        }
        
        
    }
    
    
    

Log in to reply
 

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