Java Binary Tree (SegmentTree Idea)
\nclass CountIntervals {\n    private TreeNode root = null;\n    public CountIntervals() {\n        root = new TreeNode();\n    }\n    public void add(int left,
```\nclass CountIntervals {\n    private TreeNode root = null;\n    public CountIntervals() {\n        root = new TreeNode();\n    }\n    public void add(int left, int right) {\n\t\t// Given number range is [1, 10^9]\n        add(root, 1, (int)(1e9+1), left, right);\n    }\n    public int add(TreeNode node, int start, int end, int left, int right) {\n\t\t// If interval is out of the node range, don\'t need to update current node, return count directly.\n        if (left > end || right < start) {\n            return node.val;\n        }\n\t\t// If the current node is fully covered, return count directly.\n        if(end - start + 1 == node.val){\n            return node.val;\n        }\n\t\t// If is the leaf node, update the node count.\n        if(start == left && end == right){\n            return node.val = end - start + 1;\n        }\n\t\t// Update the children tree nodes when needed(the interval added is between the node range)\n        int mid = start + (end - start) / 2;\n        if(node.left == null){\n            node.left = new TreeNode();\n        }\n        if(node.right == null){\n           node.right = new TreeNode(); \n        }\n        int cnt = 0;\n        cnt += add(node.left, start, mid, Math.max(start, left), Math.min(mid, right));\n        cnt += add(node.right, mid+1, end, Math.max(mid+1, left), Math.min(end, right));\n        return node.val = cnt;\n    }\n    public int count() {\n        return root.val;\n    }\n}\n```
['Binary Search Tree', 'Java']