AC Java solution 3ms, explanation super simple to understand

  • 0

    We need to find the second min value. This value can be :

    • the last element we compared to the winner (the root)
    • some value that the winner beat before

    This gives us an easy recursion that we can follow to find this min value.

    We encode the end of the recursion as MAX_INT so that any value that we compare before is lesser than this. But then we need to make sure that if it is an exception case (like there is only one node in the tree) we return the -1 exception value.

       public int findSecondMinimumValue(TreeNode root) {
            int ret = helper(root, root.val);
            if (ret == Integer.MAX_VALUE) {
                return -1;
            return ret;
        private int helper(TreeNode node, int rootVal) {
            if (node.left == null || node.right == null) {
                return Integer.MAX_VALUE;
            if(node.left.val == rootVal && node.right.val == rootVal) {
                return Math.min(helper(node.left, rootVal), helper(node.right, rootVal));
            } else if (node.right.val == rootVal) {
                return Math.min(node.left.val, helper(node.right, rootVal));
            } else {
                return Math.min(node.right.val, helper(node.left, rootVal));

Log in to reply

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