I know the time complexity of basic operations such as add, get is O(logn). But I didn't found the detail of lower() and higher(). So, what is the time complexity of lower() and higher() of TreeSet in Java?
TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet.
TreeMap has complexity of O(logN) for insertion and lookup.
The TreeSet stores the objects in the ascending order, which is a natural ordering of a tree.
TreeSet uses the Set underlying data structure. In PriorityQueue, apart from the root rest of the elements may or may not follow any order. In TreeSet all the elements remain in the sorted order. Using PriorityQueue, we can retrieve largest or smallest element in O(1) time.
TreeSet is backed by an implementation of NavigableMap called TreeMap. The code ultimately called when computing lower() on TreeSet is lowerEntry() on TreeMap.
/**
* Returns the entry for the greatest key less than the specified key; if
* no such entry exists (i.e., the least key in the Tree is greater than
* the specified key), returns {@code null}.
*/
final Entry<K,V> getLowerEntry(K key) {
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
if (cmp > 0) {
if (p.right != null)
p = p.right;
else
return p;
} else {
if (p.left != null) {
p = p.left;
} else {
Entry<K,V> parent = p.parent;
Entry<K,V> ch = p;
while (parent != null && ch == parent.left) {
ch = parent;
parent = parent.parent;
}
return parent;
}
}
}
return null;
}
Looking at this code, it looks like with each iteration of the while loop, every branch either returns or traverse one level of the tree. Since Tree Map should have log(n)
levels, the entire method has O(log(n))
complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With