forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment-tree-query-ii.cpp
42 lines (38 loc) · 1.11 KB
/
segment-tree-query-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Time: O(h)
// Space: O(h)
/**
* Definition of SegmentTreeNode:
* class SegmentTreeNode {
* public:
* int start, end, count;
* SegmentTreeNode *left, *right;
* SegmentTreeNode(int start, int end, int count) {
* this->start = start;
* this->end = end;
* this->count = count;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
*@param root, start, end: The root of segment tree and
* an segment / interval
*@return: The count number in the interval [start, end]
*/
int query(SegmentTreeNode *root, int start, int end) {
// Out of range.
if (root == nullptr || root->start > end || root->end < start) {
return 0;
}
// Current segment is totally within range [start, end]
if (root->start >= start && root->end <= end) {
return root->count;
}
int left = query(root->left, start, end);
int right = query(root->right, start, end);
// Find max in the children.
return left + right;
}
};