Skip to content

Commit fd4875a

Browse files
authored
Merge pull request #175 from SaBuZa/Fenwick-Tree
Add Fenwick Tree
2 parents 64610bc + d68d0ef commit fd4875a

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: data_structures/Binary Tree/FenwickTree.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class FenwickTree:
2+
3+
def __init__(self, SIZE): # create fenwick tree with size SIZE
4+
self.Size = SIZE
5+
self.ft = [0 for i in range (0,SIZE)]
6+
7+
def update(self, i, val): # update data (adding) in index i in O(lg N)
8+
while (i < self.Size):
9+
self.ft[i] += val
10+
i += i & (-i)
11+
12+
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
13+
ret = 0
14+
while (i > 0):
15+
ret += self.ft[i]
16+
i -= i & (-i)
17+
return ret
18+
19+
if __name__ == '__main__':
20+
f = FenwickTree(100)
21+
f.update(1,20)
22+
f.update(4,4)
23+
print (f.query(1))
24+
print (f.query(3))
25+
print (f.query(4))
26+
f.update(2,-5)
27+
print (f.query(1))
28+
print (f.query(3))

0 commit comments

Comments
 (0)