Algorithms

TreeSet / Binary Search Tree

๐Ÿ“‹ Quick Reference

PropertyValue
TypeSorted set backed by Red-Black Tree
Add/Remove/ContainsO(log n)
First/LastO(log n)
MemoryO(n) with node overhead
OrderingNatural order or custom Comparator
Best ForSorted unique elements, range queries
One-liner: Self-balancing BST providing O(log n) sorted operations with no duplicates.

๐ŸŽฎ Interactive Visualizer

Watch how TreeSet maintains balance during insertions and deletions:

Loading visualizer...
Try these operations:
  1. Insert elements - see tree balancing (rotations)
  2. Delete a node - watch restructuring
  3. Find an element - observe O(log n) path
  4. Try inserting duplicates - they're ignored!

๐Ÿ”ง Key Operations

Creating

JAVA(9 lines)
Code
Loading syntax highlighter...

Adding/Removing

JAVA(7 lines)
Code
Loading syntax highlighter...

Querying

JAVA(7 lines)
Code
Loading syntax highlighter...
JAVA(15 lines)
Code
Loading syntax highlighter...

Iteration

JAVA(8 lines)
Code
Loading syntax highlighter...

๐Ÿ“Š Complexity Analysis

OperationTimeNotes
add(e)O(log n)Tree traversal + possible rebalancing
remove(e)O(log n)Find + restructure
contains(e)O(log n)Binary search in tree
first/lastO(log n)Traverse to leftmost/rightmost
floor/ceilingO(log n)Modified binary search
subSet/headSet/tailSetO(1)Returns view, not copy
iterationO(n)In-order traversal

Red-Black Tree Properties

1. Every node is RED or BLACK
2. Root is BLACK
3. Leaves (NIL) are BLACK
4. RED node โ†’ both children BLACK
5. All paths from node to leaves have same BLACK count

These rules ensure: height โ‰ค 2 ร— log(n+1)

โœ… When to Use TreeSet

Good Use Cases

  • Sorted unique elements - always in order
  • Range queries - subSet, headSet, tailSet
  • Finding neighbors - floor, ceiling, lower, higher
  • Min/Max operations - first(), last()

Avoid When

  • Just need uniqueness - use HashSet (O(1) vs O(log n))
  • Frequent contains checks - HashSet is faster
  • Need index access - TreeSet has no get(i)
  • Null elements needed - TreeSet doesn't allow null

๐Ÿ”„ TreeSet vs HashSet vs LinkedHashSet

FeatureHashSetLinkedHashSetTreeSet
OrderNoneInsertionSorted
add/containsO(1)O(1)O(log n)
MemoryLowestMediumHighest
Null allowedYesYesNo
Range queriesNoNoYes
JAVA(4 lines)
Code
Loading syntax highlighter...

โš ๏ธ Common Pitfalls

1. Inconsistent Comparator with equals

JAVA(10 lines)
Code
Loading syntax highlighter...

2. Mutating Elements After Insert

JAVA(10 lines)
Code
Loading syntax highlighter...

3. Using Non-Comparable Types

JAVA(6 lines)
Code
Loading syntax highlighter...

4. Expecting O(1) Like HashSet

JAVA(8 lines)
Code
Loading syntax highlighter...

๐ŸŽค Interview Tips

Q: What's the difference between TreeSet and HashSet?
"

TreeSet maintains sorted order using a Red-Black tree (O(log n) operations), while HashSet uses hashing (O(1) average). Choose TreeSet when you need sorted iteration or range queries; HashSet otherwise.

Q: Why can't TreeSet contain null?
"

TreeSet relies on comparisons to position elements. Comparing with null would throw NullPointerException. HashSet allows one null because it uses equals() for comparison.

Q: How does TreeSet handle duplicates?
"

Elements are compared using compareTo() or the Comparator. If comparison returns 0, elements are considered equal and the duplicate is not added. This is why Comparator should be consistent with equals().

Q: What's floor() vs lower()?
"

floor(e) returns greatest element โ‰ค e (inclusive), lower(e) returns greatest element < e (exclusive). Similarly, ceiling is โ‰ฅ and higher is >.


๐Ÿ“š Series Navigation

Previous: Part 3: HashMap

Visualizer: TreeSet from @tomaszjarosz/react-visualizers