Tree Set is a sorted set implementation using a balanced binary search tree (Red-Black Tree).
Key Characteristics:
Binary Search Tree Property: For each node, all elements in the left subtree are smaller, and all elements in the right subtree are larger.
Self-Balancing: The tree automatically maintains balance to ensure O(log n) performance, preventing degeneration into a linked list.
Aspect | Hash Set | Tree Set |
---|---|---|
Time Complexity | O(1) average | O(log n) |
Ordering | No order | Sorted order |
Implementation | Hash table | Binary search tree |
Memory Usage | Lower | Higher (tree nodes) |
Range Operations | Not supported | Efficient |
Iteration Order | Unpredictable | Sorted |
Best Use Case | Fast lookups | Sorted data |
Operation | Average | Worst |
---|---|---|
Add | O(log n) | O(log n) |
Contains | O(log n) | O(log n) |
Remove | O(log n) | O(log n) |
Traversal | O(n) | O(n) |
Component | Space |
---|---|
Tree Storage | O(n) |
Recursion Stack | O(log n) |
Choose Hash Set when:
Choose Tree Set when: