线段树的修改
题目
对于一棵 最大线段树, 每个节点包含一个额外的 max 属性,用于存储该节点所代表区间的最大值。
设计一个 modify 的方法,接受三个参数 root、 index 和 value。该方法将 root 为跟的线段树中 [start, end] = [index, index] 的节点修改为了新的 value ,并确保在修改后,线段树的每个节点的 max 属性仍然具有正确的值。注意事项
在做此题前,最好先完成线段树的构造和 线段树查询这两道题目。样例
对于线段树:
如果调用 modify(root, 2, 4), 返回:
或 调用 modify(root, 4, 0), 返回:
挑战
时间复杂度 O(h) , h 是线段树的高度
题解
非叶子节点的max是其左右子节点的max值中大的那个。所以先递归找到start和end都等于index的叶子节点,更新其max为value,在逐级弹栈时更新每个节点的max值。
/**
* Definition of SegmentTreeNode:
* public class SegmentTreeNode {
* public int start, end, max;
* public SegmentTreeNode left, right;
* public SegmentTreeNode(int start, int end, int max) {
* this.start = start;
* this.end = end;
* this.max = max
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
*@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
*/
public void modify(SegmentTreeNode root, int index, int value) {
if (index == root.start && index == root.end)
{
root.max = value;
return;
}
int mid = (root.start + root.end) / 2;
modify(index <= mid ? root.left : root.right,index,value);
root.max = Math.max(root.left.max,root.right.max);
}
}
Last Update 2016.11.4
619

被折叠的 条评论
为什么被折叠?



