# Java divide and conquer solution

• for left and right sub-node, if their value is the same with the parent node value, need to using recursion to find the next candidate, otherwise use their node value as the candidate.

public int findSecondMinimumValue(TreeNode root) {
if (root == null) {
return -1;
}
if (root.left == null && root.right == null) {
return -1;
}

int left = root.left.val;
int right = root.right.val;

// if value same as root value, need to find the next candidate
if (root.left.val == root.val) {
left = findSecondMinimumValue(root.left);
}
if (root.right.val == root.val) {
right = findSecondMinimumValue(root.right);
}

if (left != -1 && right != -1) {
return Math.min(left, right);
} else if (left != -1) {
return left;
} else {
return right;
}
}

• This post is deleted!

• @ttZack Concise solution

public int findSecondMinimumValue(TreeNode root) {
if(root==null)  return -1;
return findSecondMinValue(root, root.val);
}

public int findSecondMinValue(TreeNode root, int min) {
if(root==null)  return -1;
if(root.val>min)   return root.val;
int leftMin = findSecondMinValue(root.left,min);
int rightMin = findSecondMinValue(root.right,min);
return (leftMin==-1 || rightMin==-1) ? Math.max(leftMin,rightMin) : Math.min(leftMin,rightMin);
}

• Is the running time be O(n) where n is the number of nodes in the tree?

• same idea, here is my Python solution. I shorten the last part

class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return -1
if not root.left and not root.right:
return -1

t1 = root.left.val
t2 = root.right.val

if root.left.val == root.val:
t1 = self.findSecondMinimumValue(root.left)
if root.right.val == root.val:
t2 = self.findSecondMinimumValue(root.right)

if t1 == -1 or t2 == -1:
return -t1*t2
else:
return min(t1, t2)

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