给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void dfs(TreeNode root, Set<Integer> uniques) {
if (root != null) {
uniques.add(root.val);
dfs(root.left, uniques);
dfs(root.right, uniques);
}
}
public int findSecondMinimumValue(TreeNode root) {
Set<Integer> uniques = new HashSet<Integer>();
dfs(root, uniques);
int min1 = root.val;
long ans = Long.MAX_VALUE;
for (int v : uniques) {
if (min1 < v && v < ans) ans = v;
}
return ans < Long.MAX_VALUE ? (int) ans : -1;
}
}