Skip to content

Commit f6696d0

Browse files
authored
Merge pull request #177 from SaBuZa/Segment-Tree
Add Segment tree
2 parents 3b69bfc + e7e8558 commit f6696d0

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Diff for: data_structures/Binary Tree/SegmentTree.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import math
2+
3+
class SegmentTree:
4+
5+
def __init__(self, N):
6+
self.N = N
7+
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
8+
9+
def left(self, idx):
10+
return idx*2
11+
12+
def right(self, idx):
13+
return idx*2 + 1
14+
15+
def build(self, idx, l, r, A):
16+
if l==r:
17+
self.st[idx] = A[l-1]
18+
else :
19+
mid = (l+r)//2
20+
self.build(self.left(idx),l,mid, A)
21+
self.build(self.right(idx),mid+1,r, A)
22+
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
23+
24+
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
25+
if r < a or l > b:
26+
return True
27+
if l == r :
28+
self.st[idx] = val
29+
return True
30+
mid = (l+r)//2
31+
self.update(self.left(idx),l,mid,a,b,val)
32+
self.update(self.right(idx),mid+1,r,a,b,val)
33+
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
34+
return True
35+
36+
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
37+
if r < a or l > b:
38+
return -math.inf
39+
if l >= a and r <= b:
40+
return self.st[idx]
41+
mid = (l+r)//2
42+
q1 = self.query(self.left(idx),l,mid,a,b)
43+
q2 = self.query(self.right(idx),mid+1,r,a,b)
44+
return max(q1,q2)
45+
46+
def showData(self):
47+
showList = []
48+
for i in range(1,N+1):
49+
showList += [self.query(1, 1, self.N, i, i)]
50+
print (showList)
51+
52+
53+
if __name__ == '__main__':
54+
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
55+
N = 15
56+
segt = SegmentTree(N)
57+
segt.build(1,1,N,A)
58+
print (segt.query(1,1,N,4,6))
59+
print (segt.query(1,1,N,7,11))
60+
print (segt.query(1,1,N,7,12))
61+
segt.update(1,1,N,1,3,111)
62+
print (segt.query(1,1,N,1,15))
63+
segt.update(1,1,N,7,8,235)
64+
segt.showData()

0 commit comments

Comments
 (0)