For a Maximum Segment Tree
, which each node has an extra value max
to store the maximum value in this node's interval.
Implement a modify
function with three parameter root
, index
and value
to change the node's value with [start, end] = [index, index] to the new given value. Make sure after this change, every node in segment tree still has the max attribute with the correct value.
Notice
We suggest you finish problem Segment Tree Build and Segment Tree Query first.
For segment tree:
[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]
if call modify(root, 2, 4)
, we can get:
[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]
or call modify(root, 4, 0)
, we can get:
[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]
Do it in O(h)
time, h is the height of the segment tree.
感觉没有章法的做题还是不是很聪明的选择。争取还是分类做吧,这样至少能够总结出一些规律出来。
今天做了下segment tree相关的题。基本上都是通过递归的写法ac的。而且思路上也有一定的关联。从二叉树引申而来,所以很明显是可以通过递归来做。
这道题先是看了一会,没什么思路,后来发现流程应该是这样的:这道题的思路是,首先通过递归找到跟节点,start = end 的节点,把它的值先更新,然后再向它的父节点一层层的返回,父节点通过左右孩子的max值更新自己的max值。因为这个更新过程是从更新的那个节点开始一层层往上的,所以但凡是需要更新的位置都会去更新。于是这道题的就好写出来了。
又因为segment tree的特点,当前的index 需要根 mid = (start+end)/2 的值进行比较,决定它是走哪条路下到根节点。 其他的就是一些边界条件的判断。
代码:
public void modify(SegmentTreeNode root, int index, int value) {
// write your code here
if(root == null) return;
if(root.start == index && root.end == index){
root.max = value;
return;
}
if(root.start > index){
modify(root.left, index, value);
}
if(root.end < index){
modify(root.right, index, value);
}
int mid = (root.start + root.end)/2;
if(index<=mid){
modify(root.left, index, value);
}else{
modify(root.right, index, value);
}
root.max = Math.max(root.left.max, root.right.max);
}