For a Maximum Segment Tree , which each node have an extra value to max store the maximum value in this node ' s interval.
Implement a modify function with three parameter root , and to change the index value node's value with [start, end] = [Index, index] To the new given value. Make sure the Every node in segment tree still have the Max attribute with the correct value.
Example
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]
Challenge
Do it O(h) in time, and H is the height of the segment tree.
/*** Definition of Segmenttreenode: * public class Segmenttreenode {* Public int start, end, Max; * Public Segm Enttreenode 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 classSolution {/** *@paramroot, index, value:the root of Segment tree and *@ Change the node's value with [Index, index] to the new given Value *@return: void*/ Public voidModify (Segmenttreenode root,intIndexintvalue) { //Write your code here if(Index > Root.end | | | Index <Root.start)return; if(Root.start = = Root.end && Root.start = =index) {Root.max=value; return; } intMID = Root.start + (Root.end-root.start)/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); return; }}
Lintcode-medium-segment Tree Modify