Sobes.tech
Junior — Middle

Kui kaua võtab aega elemendi sisestamine andmestruktuuri TreeSet?

sobes.tech AI

Vastus AI-lt

In Java, the data structure TreeSet is implemented based on a red-black tree, which ensures ordered storage of elements.

Adding an element to TreeSet takes approximately O(log n) time, where n is the number of elements in the set. This is due to the need to find the correct position for insertion and to maintain the tree's balance.

Example:

TreeSet<Integer> set = new TreeSet<>();
set.add(10); // insertion in O(log n)
set.add(5);
set.add(20);

Therefore, insertion into TreeSet is efficient and suitable for cases where an ordered set without duplicates is required.