-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSegment_Tree_Node_query.cpp
More file actions
77 lines (68 loc) · 1.73 KB
/
Segment_Tree_Node_query.cpp
File metadata and controls
77 lines (68 loc) · 1.73 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition of SegmentTreeNode:
* class SegmentTreeNode {
* public:
* int start, end, max;
* SegmentTreeNode *left, *right;
* SegmentTreeNode(int start, int end, int max) {
* this->start = start;
* this->end = end;
* this->max = max;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
*@param root, start, end: The root of segment tree and
* an segment / interval
*@return: The maximum number in the interval [start, end]
*/
int query(SegmentTreeNode *root, int start, int end) {
// write your code here
if(root == NULL) // should never happen
{
return numeric_limits<int>::min();
}
if(start == root->start && end == root->end)
{
return root->max;
}
int mid = (root->start + root->end) / 2;
int leftMax = numeric_limits<int>::min(), rightMax = numeric_limits<int>::min();
if(start <= mid) // 左子区
{
if(mid < end)
{
leftMax = query(root->left, start, mid);
}
else
{
leftMax = query(root->left, start, end);
}
}
if(mid < end) // 右子区
{
if(start <= mid)
{
rightMax = query(root->right, mid+1, end);
}
else
{
rightMax = query(root->right, start, end);
}
}
return max(leftMax, rightMax);
}
};
对于数组 [1, 4, 2, 3],
[0, 3, max=4]
/ \
[0,1,max=4] [2,3,max=3]
/ \ / \
[0,0,max=1] [1,1,max=4] [2,2,max=2], [3,3,max=3]
query(root, 1, 1), return 4
query(root, 1, 2), return 4
query(root, 2, 3), return 3
query(root, 0, 2), return 4