Recursive Java solution


  • 0
    H

    If the value of the left(right) node is greater than the value of the root node, it is the candidate from the left(right) side, otherwise the 2nd minimum value of the left(right) subtree is the candidate. Then we compare the candidates from both sides, check for -1, and return.

    class Solution {
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null || root.left == null || root.right == null) return -1;
            int leftSecondMinVal = (root.left.val > root.val) ? root.left.val : findSecondMinimumValue(root.left);
            int rightSecondMinVal = (root.right.val > root.val) ? root.right.val : findSecondMinimumValue(root.right);
            if (leftSecondMinVal != -1 && rightSecondMinVal != -1) return Math.min(leftSecondMinVal, rightSecondMinVal);
            return (leftSecondMinVal != -1) ? leftSecondMinVal : rightSecondMinVal;
        }
    }
    

Log in to reply
 

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