题目地址:
https://www.lintcode.com/problem/segment-tree-modify/description
给定一个存一个数组的区间最大值的线段树,现在要将数组中某个位置 i i i的数改为 v v v,要求返回数组改变后的对应的线段树。
思路是递归。先将 i i i这个位置对应的线段树中的叶子节点更新,然后递归回去的时候把父节点存储的最大值更新即可。代码如下:
public class Solution {
/**
* @param root: The root of segment tree.
* @param index: index.
* @param value: value
* @return: nothing
*/
public void modify(SegmentTreeNode root, int index, int value) {
// write your code here
// 如果走到了对应的叶子,则更新值
if (root.start == root.end && root.start == index) {
root.max = value;
return;
}
// 求区间中点
int mid = root.start + (root.end - root.start >> 1);
// 如果要更新的值的下标在左半区间,那就向左子树递归
if (index <= mid) {
modify(root.left, index, value);
}
if (index > mid) {
modify(root.right, index, value);
}
// 更新根节点
root.max = Math.max(root.left.max, root.right.max);
}
}
class SegmentTreeNode {
int start, end, max;
SegmentTreeNode left, right;
public SegmentTreeNode(int start, int end, int max) {
this.start = start;
this.end = end;
this.max = max;
}
}
时空复杂度 O ( log n ) O(\log n) O(logn), n n n是数组长度。