-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSegment Tree Build II.cpp
42 lines (41 loc) · 1.21 KB
/
Segment Tree Build 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
/**
* 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 A: a list of integer
*@return: The root of Segment Tree
*/
SegmentTreeNode * build(vector<int>& A) {
// write your code here
return build(0, A.size()-1, A);
}
SegmentTreeNode * build(int start, int end, vector<int>& A) {
// write your code here
if(start > end) return nullptr;
if(start == end) {
SegmentTreeNode *tree = new SegmentTreeNode(start, end, A[start]);
return tree;
}
if(start < end) {
SegmentTreeNode * left = build(start, (start+end)/2, A);
SegmentTreeNode * right = build((start+end)/2+1, end, A);
SegmentTreeNode *tree = new SegmentTreeNode(start, end, max(left->max, right->max));
tree -> left = left;
tree -> right = right;
return tree;
}
}
};