问题描述
笔记
比较左孩子的end
与index
,如果index<=root->left->end
说明index
在左子树,那就递归修改左子树,否则递归修改右子树。最后把root
的max
值更新。
代码
/**
* 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 (root == NULL)
return;
if (root->start==root->end)
{
root->max = value;
return;
}
if (index <= root->left->end)
modify(root->left, index, value);
else
modify(root->right, index, value);
root->max = max(root->left->max, root->right->max);
}
};