题目
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
答案
class Solution {
/*
The minimum value is always the root, but what about the second minimum?
try to find the minimum value of the left and right tree
*/
public int findSecondMinimumValue(TreeNode root) {
if(root == null) return -1;
int ret = findmin(root, root.val);
if(ret == Integer.MAX_VALUE) return -1;
return ret;
}
public int findmin(TreeNode root, int exclude) {
if(root == null) return Integer.MAX_VALUE;
int left = findmin(root.left, exclude);
int right = findmin(root.right, exclude);
int rootval = root.val;
if(left == exclude) left = Integer.MAX_VALUE;
if(right == exclude) right = Integer.MAX_VALUE;
if(rootval == exclude) rootval = Integer.MAX_VALUE;
return Math.min(rootval, Math.min(left, right));
}
}