JAVA SOLUTION
\nclass CountIntervals {\n    TreeMap<Integer, Integer> m;\n    int count = 0;\n\n    public CountIntervals() {\n        m = new TreeMap<>();\n    }\n\n    publ
```\nclass CountIntervals {\n    TreeMap<Integer, Integer> m;\n    int count = 0;\n\n    public CountIntervals() {\n        m = new TreeMap<>();\n    }\n\n    public void add(int left, int right) {\n        int start = left, end = right;\n\n        while (m.floorKey(end) != null && start <= m.get(m.floorKey(end)) && end >= m.floorKey(end)) {\n            int l = m.floorKey(end);\n            int r = m.get(l);\n            count -= r - l + 1;\n            m.remove(l);\n\n            start = Math.min(start, l);\n            end = Math.max(end, r);\n        }\n\n        count += end - start + 1;\n        m.put(start, end);\n    }\n\n    public int count() {\n        return count;\n    }\n}\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = new CountIntervals();\n * obj.add(left,right);\n * int param_2 = obj.count();\n */\n```
['Tree', 'Java']