TreeSet
Code
# Code
```java []
class CountIntervals {
    private int count;
    private TreeMap<Integer, Integer> intervals = new TreeMap<>();

    public CountIntervals() {
    }

    public void add(int left, int right) {
        right++;
        Map.Entry<Integer, Integer> lower = intervals.floorEntry(left);
        if (lower != null && lower.getValue() >= left) {
            left = lower.getKey();
            intervals.remove(lower.getKey());
            right = Math.max(right, lower.getValue());
            count -= lower.getValue() - lower.getKey();
        }
        while (true) {
            lower = intervals.floorEntry(right);
            if (lower == null || lower.getKey() < left) {
                break;
            }
            right = Math.max(right, lower.getValue());
            intervals.remove(lower.getKey());
            count -= lower.getValue() - lower.getKey();
        }
        count += right - left;
        intervals.put(left, right);
    }

    public int count() {
        return count;
    }
}

/**
 * Your CountIntervals object will be instantiated and called as such:
 * CountIntervals obj = new CountIntervals();
 * obj.add(left,right);
 * int param_2 = obj.count();
 */
```
['Java']