/** 307. Range Sum query-mutable * 2016-7-3 by Mingyang * Insane segment Tree, no words anymore*/classNumarray {classSegmenttreenode {intstart, end; Segmenttreenode left, right; intsum; PublicSegmenttreenode (intStartintend) { This. Start =start; This. end =end; This. left =NULL; This. right =NULL; This. Sum = 0; }} Segmenttreenode Root=NULL; PublicNumarray (int[] nums) {Root= Buildtree (nums, 0, Nums.length-1); } PrivateSegmenttreenode Buildtree (int[] Nums,intStartintend) { if(Start >end) { return NULL; } Else{segmenttreenode ret=NewSegmenttreenode (start, end); if(Start = =end) {Ret.sum=Nums[start]; } Else { intMID = start + (End-start)/2; Ret.left=Buildtree (Nums, start, mid); Ret.right= Buildtree (Nums, Mid + 1, end); Ret.sum= Ret.left.sum +ret.right.sum; } returnret; } } voidUpdateintIintval) {Update (root, I, Val); } voidUpdate (Segmenttreenode root,intPosintval) { if(Root.start = =root.end) {root.sum=Val; } Else { intMID = Root.start + (Root.end-root.start)/2; if(Pos <=mid) {Update (Root.left, POS, Val); } Else{update (Root.right, POS, Val); } root.sum= Root.left.sum +root.right.sum; } } Public intSumrange (intIintj) {returnSumrange (Root, I, j); } Public intSumrange (Segmenttreenode root,intStartintend) { if(Root.end = = End && Root.start = =start) { returnroot.sum; } Else { intMID = Root.start + (Root.end-root.start)/2; if(End <=mid) {returnSumrange (Root.left, start, end); } Else if(Start >= mid+1) { returnSumrange (root.right, start, end); } Else { returnSumrange (Root.right, mid+1, end) +Sumrange (Root.left, start, mid); } } }}
307. Range Sum query-mutable