返回树中第二小的节点。
中序遍历将节点放在set集合中,将set集合转换成list,并排序,返回第二位的值。
class Solution {
HashSet<Integer> set = new HashSet<Integer>();
public int findSecondMinimumValue(TreeNode root) {
//将树遍历存在set集合中
Bianli(root);
ArrayList<Integer> list=new ArrayList<>(set);
Collections.sort(list);
if(list.size()==1) return -1;
return list.get(1);
}
public void Bianli(TreeNode root){
if(root!=null){
Bianli(root.left);
set.add(root.val);
Bianli(root.right);
}
}
}