Junior — Middle
How is the time complexity of adding an element to a TreeSet evaluated?
sobes.tech AI
Answer from AI
In Java, the TreeSet class is implemented based on a red-black tree, which is a balanced binary search tree. The time complexity of adding an element to a TreeSet is O(log n), where n is the number of elements in the set.
This is because, for insertion, the element is first searched in the tree to find the correct position, and then the tree is balanced, which takes logarithmic time.
Example:
TreeSet<Integer> set = new TreeSet<>();
set.add(10); // O(log n)
set.add(5); // O(log n)
set.add(20); // O(log n)