码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode203 Segment Tree Modify solution 题解

时间:2018-02-17 20:30:00      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:zha   www.   query   lintcode   attribute   授权   attr   最好   com   

【题目描述】

 

 

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.

对于一棵最大线段树, 每个节点包含一个额外的max属性,用于存储该节点所代表区间的最大值。

设计一个modify的方法,接受三个参数root、index和value。该方法将root为根的线段树中 [start,end] = [index,index] 的节点修改为了新的value,并确保在修改后,线段树的每个节点的max属性仍然具有正确的值。

【注】:在做此题前,最好先完成线段树的构造线段树查询这两道题目。

【题目链接】

www.lintcode.com/en/problem/segment-tree-modify/

【题目解析】

此题依然可使用递归。

非叶子节点的max是其左右子节点的max值中大的那个。所以先递归找到start和end都等于index的叶子节点,更新其max为value,在逐级弹栈时更新每个节点的max值。

注意:若树的结点范围为0~n,那么至少有n/2个数在左子树上,所以if语句里用了<=号。另外,最后一句root.max = Math.max(root.left.max, root.right.max)是调用递归之后的结果,必须写在最后面。

【参考答案】

www.jiuzhang.com/solutions/segment-tree-modify/



作者:程风破浪会有时
链接:https://www.jianshu.com/p/57b56a77c947
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Lintcode203 Segment Tree Modify solution 题解

标签:zha   www.   query   lintcode   attribute   授权   attr   最好   com   

原文地址:https://www.cnblogs.com/admondguo/p/8452133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!