题目描述:
For an integer array (index from 0 to n-1, where n is the size of this array), in the corresponding SegmentTree, each node stores an extra attribute max
to denote the maximum number in the interval of the array (index from start to end).
Design a query
method with three parameters root
, start
and end
, find the maximum number in the interval [start, end] by the given root of segment tree.
Notice
It is much easier to understand this problem if you finished Segment Tree Build first.
For array [1, 4, 2, 3]
, the corresponding Segment Tree is:
[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
对于当前root的query等于在root->left和root->right的query中取最大值。对于segment tree来说,只有当start和end match上它root的start和end时,才会有已知的值返回;如果start和end只和它的start/end有overlap,那么需要继续call它的子树(更细分的区间)来寻求答案。这就是recursion的思想。
Mycode(AC = 689ms):
/**
* 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 (start > end || root == NULL) {
return INT_MIN;
}
else if (root->start == start && root->end == end) {
return root->max;
}
else {
// get max of left root and right root results
int left = query(root->left,
max(start, root->start),
min(end, (root->start + root->end) / 2));
int right = query(root->right,
max(start, (root->start + root->end) / 2 + 1),
min(end, root->end));
return max(left, right);
}
}
};