MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / update

Method update

Java/Range-Sum-Query-Mutable.java:36–51  ·  view source on GitHub ↗
(int pos, int val)

Source from the content-addressed store, hash-verified

34
35 // update the segment tree if new value to be inserted in tree, then update its parent at pos/2 and so on till root
36 void update(int pos, int val) {
37 pos += n;
38 tree[pos] = val;
39 while (pos > 0) {
40 int left = pos;
41 int right = pos;
42 if (pos % 2 == 0) {
43 right = pos + 1;
44 } else {
45 left = pos - 1;
46 }
47 // parent is updated after child is updated
48 tree[pos / 2] = tree[left] + tree[right];
49 pos /= 2;
50 }
51 }
52
53
54 // this is responsible for the sum betweeen given ranges

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected