TreeSet is supported by a NavigableMap implementation called TreeMap. The code that is ultimately called when lower () is calculated in the TreeSet is lowerEntry () on the TreeMap.
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, each branch returns or traverses one level of the tree. Since the tree map must have levels log(n), the whole method has complexity O(log(n)).
source
share