对于一棵 最大线段树, 每个节点包含一个额外的 max
属性,用于存储该节点所代表区间的最大值。
设计一个 modify
的方法,接受三个参数 root
、 index
和value
。该方法将 root 为跟的线段树中 [start, end] = [index, index] 的节点修改为了新的 value ,并确保在修改后,线段树的每个节点的 max 属性仍然具有正确的值。
样例
对于线段树:
[1, 4, max=3]
/ \
[1, 2, max=2] [3, 4, max=3]
/ \ / \
[1, 1, max=2], [2, 2, max=1], [3, 3, max=0], [4, 4, max=3]
如果调用 modify(root, 2, 4)
, 返回:
[1, 4, max=4]
/ \
[1, 2, max=4] [3, 4, max=3]
/ \ / \
[1, 1, max=2], [2, 2, max=4], [3, 3, max=0], [4, 4, max=3]
或 调用 modify(root, 4, 0)
, 返回:
[1, 4, max=2]
/ \
[1, 2, max=2] [3, 4, max=0]
/ \ / \
[1, 1, max=2], [2, 2, max=1], [3, 3, max=0], [4, 4, max=0]
挑战
时间复杂度 O(h)
, h 是线段树的高度
/**
* 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, index, value: The root of segment tree and
*@ change the node's value with [index, index] to the new given value
*@return: void
*/
void modify(SegmentTreeNode *root, int index, int value) {
// write your code here
if (NULL == root)
{
return;
}
if (index < root->left->start || index > root->right->end)
{
return;
}
SegmentTreeNode *p = root;
if (value >= root->max)
{
while (p->left != NULL)
{
p->max = value;
if (index <= p->left->end)
{
p = p->left;
}
else
{
p = p->right;
}
}
p->max = value;
}
else
{
p = root;
while (p->start != index || p->end != index)
{
if (index <= p->left->end)
{
p = p->left;
}
else
{
p = p->right;
}
}
p->max = value;
SegmentTreeNode *q = root;
while (p != root)
{
q = root;
while (q->left != p && q->right != p)
{
if (index <= q->left->end)
{
q = q->left;
}
else
{
q = q->right;
}
}
int temp = max(q->left->max, q->right->max);
if (temp == q->max)
{
break;
}
else
{
q->max = temp;
p = q;
}
}
}
}
};