Skip to content

Commit 590dfc5

Browse files
Add Segment Tree Data Structure
1 parent 15b2124 commit 590dfc5

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Data_Structure/src/segment_tree.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
from typing import TypeVar, List, Callable
2+
from functools import reduce
3+
4+
5+
T = TypeVar('T') # Basic Template allowing any variable as input.
6+
7+
8+
def build(arr: List[T], n: int, func: Callable[[T, T], T]) -> List[T]:
9+
"""
10+
builds the trees from the passed list.
11+
Time Complexity: O(n)
12+
13+
Parameters
14+
----------
15+
arr: iterable
16+
list of elements to be added to the data structure
17+
func: Callable
18+
function that will be binary operator
19+
20+
Returns
21+
-------
22+
Built Segment Tree
23+
"""
24+
tree = [0 for i in range(n)]
25+
tree.extend(arr)
26+
for i in range(n-1, 0, -1):
27+
tree[i] = func(tree[i << 1], tree[i << 1 | 1])
28+
return tree
29+
30+
31+
def point_update(tree: List[T], n: int, pos: int, val: int, func: Callable[[T, T], T]) -> None:
32+
"""
33+
Updates the tree with given value.
34+
Time Complexity: O(lgn)
35+
36+
Parameters
37+
----------
38+
tree: list
39+
built segment tree
40+
n: int
41+
size of segment tree
42+
pos: int
43+
index which is to be updated.
44+
val: int
45+
the value with which arr[pos] is to be updated.
46+
func: Callable
47+
binary operator which will be applied to the input parameters.
48+
"""
49+
pos += n
50+
tree[pos] = val
51+
while pos > 1:
52+
tree[pos >> 1] = func(tree[pos], tree[pos ^ 1])
53+
pos >>= 1
54+
55+
56+
def query(tree: List[T], l: int, r: int, n: int, func: Callable[[T, T], T], start_ans=0, right_inclusive=True):
57+
"""
58+
Parameters
59+
----------
60+
tree: segment Tree
61+
l: left
62+
r: right
63+
n: max size of array
64+
func: Callable to be operated on the input parameters.
65+
start_ans: seed value with which run is to be initialised
66+
"""
67+
68+
l += n
69+
r += n + right_inclusive
70+
ans = start_ans
71+
while l < r:
72+
if l & 1:
73+
ans = func(ans, tree[l])
74+
l += 1
75+
if r & 1:
76+
r -= 1
77+
ans = func(ans, tree[r])
78+
l >>= 1
79+
r >>= 1
80+
return ans
81+
82+
83+
84+
if __name__ == '__main__':
85+
arr = [3, 2, 4, 5, 6, 8, 2, 4, 5]
86+
n = len(arr)
87+
func = int.__mul__
88+
tree = build(arr, n, func)
89+
point_update(tree, n, 0, 0, func)
90+
l, r = 2, 4
91+
assert query(tree, l, r, n, func, start_ans=1) == reduce(func, arr[l: r+1]), "Segment Tree faulty"
92+

0 commit comments

Comments
 (0)