Junior — Middle
How is the efficiency of searching for an element in a TreeSet data structure evaluated?
sobes.tech AI
Answer from AI
In Java, the TreeSet data structure is implemented based on a red-black tree — a balanced binary search tree. The efficiency of searching for an element in a TreeSet is estimated as O(log n), where n is the number of elements in the set.
This is because, for searching, the element is compared with the nodes of the tree, moving either to the left or right subtree, which reduces the number of checks logarithmically.
Example of using TreeSet:
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(10);
treeSet.add(5);
treeSet.add(20);
boolean contains = treeSet.contains(5); // search in O(log n)