10 lines, very simple Java solution, preorder traversal

  • 0

    As you can tell, it is very simple and very easy to understand. Use an array to keep the range (lower bound, upper bound), do preorder traverse, check if there is any value val that : val > lower bound (root.val) and val < upper bound.

    public int findSecondMinimumValue(TreeNode root) {
            int[] range = new int[]{root.val, Integer.MAX_VALUE};
            findValue(root, range);
            return range[1] == Integer.MAX_VALUE ? -1 : range[1];
        private void findValue(TreeNode root, int[] range) {
            if (root == null) return ;
            if (root.val > range[0] && root.val < range[1])
                range[1] = root.val;
            findValue(root.left, range);
            findValue(root.right, range);

Log in to reply

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