forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegment-tree-build.cpp
43 lines (37 loc) · 1.11 KB
/
segment-tree-build.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
43
// Time: O(n)
// Space: O(h) = O(logn)
/**
* Definition of SegmentTreeNode:
* class SegmentTreeNode {
* public:
* int start, end;
* SegmentTreeNode *left, *right;
* SegmentTreeNode(int start, int end) {
* this->start = start, this->end = end;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
*@param start, end: Denote an segment / interval
*@return: The root of Segment Tree
*/
SegmentTreeNode * build(int start, int end) {
if (start > end) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeNode *root = new SegmentTreeNode(start, end);
// If start equals to end, there will be no children for this node.
if (start == end) {
return root;
}
// Left child: start=A.left, end=(A.left + A.right) / 2.
root->left = build(start, (start + end) / 2);
// Right child: start=(A.left + A.right) / 2 + 1, end=A.right.
root->right = build((start + end) / 2 + 1, end);
return root;
}
};