Simple Java Solution, DFS


  • 0
    F

    Just traverse the whole tree and search the second minimum value.

    class Solution {
        int min2 = Integer.MAX_VALUE;
        public int findSecondMinimumValue(TreeNode root) {
            dfs(root, root.val);
            return min2 == Integer.MAX_VALUE? -1 : min2;
        }
        public void dfs(TreeNode root, int min) {
            if (root == null) {
                return;
            }
            if (root.val != min &&  root.val - min < min2 - min) {
                min2 = root.val;
            }
            dfs(root.left, min);
            dfs(root.right, min);
        }
    }
    

Log in to reply
 

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