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] = [I Ndex, 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]
1 /**2 * Definition of Segmenttreenode:3 * public class Segmenttreenode {4 * public int start, end, Max;5 * Public Segmenttreenode left and right;6 * Public Segmenttreenode (int start, int end, int max) {7 * This.start = start;8 * this.end = end;9 * This.max = MaxTen * This.left = This.right = null; One * } A * } - */ - Public classSolution { the /** - * @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 voidModify (Segmenttreenode root,intIndexintvalue) { + changeandupdate (root, index, value); A } at - Private voidChangeandupdate (Segmenttreenode root,intIndexintvalue) { - if(Root.start = = Index && Root.end = =index) { -Root.max =value; - return; - } in - intMid = (Root.start + root.end)/2; to if(Mid >=index) { + Change (root.left, index, value); -}Else { the Change (root.right, index, value); * } $Root.max =Math.max (Root.left.max, Root.right.max);Panax Notoginseng } -}
Segment Tree Modify