🧠 Quick Answer:
If you add elements to a
TreeSet
in ascending order, it still works perfectly, and the set remains balanced internally, becauseTreeSet
uses a red-black tree, which self-balances on every insertion.
📦 Under the hood:
TreeSet
is backed by a TreeMap
, which is implemented as a red-black tree — a type of self-balancing binary search tree.
That means:
- No matter the insertion order (ascending, descending, random),
- The tree will restructure itself after each insert to maintain O(log n) performance for:
add()
remove()
contains()
- Iteration (which returns sorted order)
💡 So unlike a basic binary search tree (BST), adding elements in sorted order will not degrade it into a “linked list” shape. Instead, the red-black tree keeps it balanced.
✅ Example:
Set<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
System.out.println(treeSet); // [1, 2, 3, 4, 5]
Even though we added in order:
- Internally: the tree is not skewed,
- Performance: still O(log n) per operation.
🔍 Visualization:
If it were a plain BST, inserting [1, 2, 3, 4, 5]
would look like this:
1
\
2
\
3
\
4
\
5
🔻 Bad: Unbalanced — behaves like a linked list → O(n) lookups
But a red-black tree would rotate nodes as needed, ending up like:
3
/ \
2 5
/ /
1 4
🔼 Good: Balanced → O(log n) operations
🧠 TL;DR
Insertion order | Performance | Tree structure |
---|---|---|
Ascending | ✅ O(log n) | ✅ Balanced |
Descending | ✅ O(log n) | ✅ Balanced |
Random | ✅ O(log n) | ✅ Balanced |
The red-black tree makes sure that even ascending order inserts stay efficient.