# Priority Queue Solution

• I just thought of putting the values in a heap and then return the second smallest.

``````class Solution {
public int findSecondMinimumValue(TreeNode root) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

if(pq.isEmpty() || pq.size()<3) return -1;

int temp = pq.poll();

while(!pq.isEmpty()){

if(temp!=pq.peek()) return pq.peek();
pq.poll();
}

return -1;

}

public static void add(TreeNode root, PriorityQueue<Integer> pq){
if(root==null) return;
return;
}
}
``````

Improvements/feedback appreciated!

``````public int findSecondMinimumValue(TreeNode root) {
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.pollFirst();
if(!ts.isEmpty()) return ts.first(); else return -1;
}``````

• This post is deleted!

• @aayushgarg Yes. I thought of treeset as well.
But adding to it also costs logn per entry, are there any time complexity improvements?

• @waltwhitman Java Priority Queue is implemented using Heap Data Structures and Heap has O(log(n)) time complexity to insert and delete element. Both TreeSet and Priority queue provides O(log(N)) complexity for adding, removing and searching elements.

Set will not store multiple duplicate elements in memory, thus improving space complexity.

• @aayushgarg Yes!!
The only gain is of space complexity otherwise time complexity remains same.
Thanks!

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