Java Solution[DFS], Easy

  • 0
    public int findSecondMinimumValue(TreeNode root) {
        if(root == null)
            return -1;
        int  res = findSecondMin(root, root.val);
        return root.val == res? -1:res;
    private int findSecondMin(TreeNode root, int prev){
        if(root == null)
            return prev;
        if(root.val != prev)
            return root.val;
        int left = findSecondMin(root.left, root.val);
        int right = findSecondMin(root.right, root.val);
        if(left == root.val && right == root.val)
            return prev;
        else if(left == root.val)
            return right;
        else if(right == root.val)
            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.