From d68d0ef05c024cb90f96b379c1206b3487847cbc Mon Sep 17 00:00:00 2001 From: Sarot Busala Date: Fri, 20 Oct 2017 16:45:17 +0700 Subject: [PATCH] Add Fenwick Tree Add Fenwick Tree (Binary Index Tree) --- data_structures/Binary Tree/FenwickTree.py | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 data_structures/Binary Tree/FenwickTree.py diff --git a/data_structures/Binary Tree/FenwickTree.py b/data_structures/Binary Tree/FenwickTree.py new file mode 100644 index 000000000..02e2d6151 --- /dev/null +++ b/data_structures/Binary Tree/FenwickTree.py @@ -0,0 +1,28 @@ +class FenwickTree: + + def __init__(self, SIZE): # create fenwick tree with size SIZE + self.Size = SIZE + self.ft = [0 for i in range (0,SIZE)] + + def update(self, i, val): # update data (adding) in index i in O(lg N) + while (i < self.Size): + self.ft[i] += val + i += i & (-i) + + def query(self, i): # query cumulative data from index 0 to i in O(lg N) + ret = 0 + while (i > 0): + ret += self.ft[i] + i -= i & (-i) + return ret + +if __name__ == '__main__': + f = FenwickTree(100) + f.update(1,20) + f.update(4,4) + print (f.query(1)) + print (f.query(3)) + print (f.query(4)) + f.update(2,-5) + print (f.query(1)) + print (f.query(3))