Skip to content

Commit faf12be

Browse files
authored
Create Segment Tree.java
1 parent ff314a2 commit faf12be

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Diff for: Trees/Segment Tree.java

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class SegmentTree {
2+
constructor(arr) {
3+
this.n = arr.length;
4+
this.tree = new Array(2 * this.n);
5+
this.build(arr);
6+
}
7+
8+
build(arr) {
9+
for (let i = 0; i < this.n; i++) {
10+
this.tree[this.n + i] = arr[i];
11+
}
12+
for (let i = this.n - 1; i > 0; --i) {
13+
this.tree[i] = this.tree[i * 2] + this.tree[i * 2 + 1];
14+
}
15+
}
16+
17+
update(index, value) {
18+
index += this.n;
19+
this.tree[index] = value;
20+
while (index > 1) {
21+
index >>= 1;
22+
this.tree[index] = this.tree[index * 2] + this.tree[index * 2 + 1];
23+
}
24+
}
25+
26+
query(left, right) {
27+
let res = 0;
28+
left += this.n;
29+
right += this.n;
30+
while (left < right) {
31+
if (left & 1) {
32+
res += this.tree[left++];
33+
}
34+
if (right & 1) {
35+
res += this.tree[--right];
36+
}
37+
left >>= 1;
38+
right >>= 1;
39+
}
40+
return res;
41+
}
42+
}
43+
44+
// Example usage
45+
let arr = [1, 3, 5, 7, 9, 11];
46+
let segTree = new SegmentTree(arr);
47+
console.log(segTree.query(1, 3)); // Output: 8
48+
segTree.update(1, 10);
49+
console.log(segTree.query(1, 3)); // Output: 15

0 commit comments

Comments
 (0)