Skip to content

Commit e3fde56

Browse files
Add Segment Tree (TheAlgorithms#2691)
1 parent 2a2cf9b commit e3fde56

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

DataStructures/Trees/SegmentTree.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package DataStructures.Trees;
2+
3+
public class SegmentTree {
4+
private int seg_t[];
5+
private int n;
6+
private int arr[];
7+
8+
/* Constructor which takes the size of the array and the array as a parameter*/
9+
public SegmentTree(int n, int arr[]) {
10+
this.n = n;
11+
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
12+
int seg_size = 2 * (int) Math.pow(2, x) - 1;
13+
14+
this.seg_t = new int[seg_size];
15+
this.arr = arr;
16+
this.n = n;
17+
constructTree(arr, 0, n - 1, 0);
18+
}
19+
20+
/* A function which will create the segment tree*/
21+
public int constructTree(int[] arr, int start, int end, int index) {
22+
if (start == end) {
23+
this.seg_t[index] = arr[start];
24+
return arr[start];
25+
}
26+
27+
int mid = start + (end - start) / 2;
28+
this.seg_t[index] = constructTree(arr, start, mid, index*2 + 1) +
29+
constructTree(arr, mid + 1, end, index*2 + 2);
30+
return this.seg_t[index];
31+
}
32+
33+
34+
/* A function which will update the value at a index i. This will be called by the
35+
update function internally*/
36+
private void updateTree(int start, int end, int index, int diff, int seg_index) {
37+
if (index < start || index > end) {
38+
return;
39+
}
40+
41+
this.seg_t[seg_index] += diff;
42+
if (start != end) {
43+
int mid = start + (end - start) / 2;
44+
updateTree(start, mid, index, diff, seg_index*2 + 1);
45+
updateTree(mid + 1, end, index, diff, seg_index*2 + 2);
46+
}
47+
}
48+
49+
/* A function to update the value at a particular index*/
50+
public void update(int index, int value) {
51+
if (index < 0 || index > n) {
52+
return;
53+
}
54+
55+
int diff = value - arr[index];
56+
arr[index] = value;
57+
updateTree(0, n - 1, index, diff, 0);
58+
}
59+
60+
/* A function to get the sum of the elements from index l to index r. This will be called internally*/
61+
private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) {
62+
if (q_start <= start && q_end >= end) {
63+
return this.seg_t[seg_index];
64+
}
65+
66+
if (q_start > end || q_end < start) {
67+
return 0;
68+
}
69+
70+
int mid = start + (end - start)/2;
71+
return getSumTree(start, mid, q_start, q_end, seg_index*2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index*2 + 2);
72+
}
73+
74+
/* A function to query the sum of the subarray [start...end]*/
75+
public int getSum(int start, int end) {
76+
if (start < 0 || end > n || start > end) {
77+
return 0;
78+
}
79+
return getSumTree(0, n-1, start, end, 0);
80+
}
81+
}

0 commit comments

Comments
 (0)