线段树是一棵二叉树,他的每个节点包含了两个额外的属性start
和end
用于表示该节点所代表的区间。start和end都是整数,并按照如下的方式赋值:
- 根节点的 start 和 end 由
build
方法所给出。 - 对于节点 A 的左儿子,有
start=A.left, end=(A.left + A.right) / 2
。 - 对于节点 A 的右儿子,有
start=(A.left + A.right) / 2 + 1, end=A.right
。 - 如果 start 等于 end, 那么该节点是叶子节点,不再有左右儿子。
对于给定数组设计一个build
方法,构造出线段树
说明
样例
给出[3,2,1,4]
,线段树将被这样构造
[0, 3] (max = 4)
/ \
[0, 1] (max = 3) [2, 3] (max = 4)
/ \ / \
[0, 0](max = 3) [1, 1](max = 2)[2, 2](max = 1) [3, 3] (max = 4)
思路:构造线段树,线段树中包含区间的开始,结束下标,以及区间内的最大值;
构造方法与基本线段树构造方法相同,只是加了最大值的属性;
/**
* 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* buildTree(int start, int end, vector<int>& A) {
if (start > end)
return NULL;
if (start == end) {
return new SegmentTreeNode(start, end, A[start]);
}
SegmentTreeNode* root = new SegmentTreeNode(start, end, A[start]);
int mid = (start + end) / 2;
root->left = buildTree(start, mid, A);
root->right = buildTree(mid + 1, end, A);
root->max=max(root->left->max,root->right->max);
return root;
}
SegmentTreeNode * build(vector<int>& A) {
// write your code here
if(A.empty())
return NULL;
return buildTree(0, A.size() - 1, A);
}
};