Concise recursive Java solution, no extra data structure


  • 0
    class Solution {
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null) {
                return -1;
            }
            return helper(root, root.val);
        }
        
        private int helper(TreeNode root, int firstMin) {
            if (root == null) {
                return -1;
            }
            if (root.val > firstMin) {
                return root.val;
            }
            int left = helper(root.left, firstMin);
            int right = helper(root.right, firstMin);
            if (left == -1) {
                return right;
            }
            if (right == -1) {
                return left;
            }
            return Math.min(left, right);
        }
    }
    

Log in to reply
 

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