From 4a2b19016068c1be5040647194e89445aadeb199 Mon Sep 17 00:00:00 2001 From: KanakalathaVemuru <46847239+KanakalathaVemuru@users.noreply.github.com> Date: Wed, 20 Oct 2021 13:49:30 +0530 Subject: [PATCH] Add Fenwick Tree (#2570) --- DataStructures/Trees/FenwickTree.java | 34 +++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DataStructures/Trees/FenwickTree.java diff --git a/DataStructures/Trees/FenwickTree.java b/DataStructures/Trees/FenwickTree.java new file mode 100644 index 000000000..65b6eb07f --- /dev/null +++ b/DataStructures/Trees/FenwickTree.java @@ -0,0 +1,34 @@ +package DataStructures.Trees; + +public class FenwickTree { + private int n; + private int fen_t[]; + + /* Constructor which takes the size of the array as a parameter */ + public FenwickTree(int n) { + this.n = n; + this.fen_t = new int[n + 1]; + } + + /* A function which will add the element val at index i*/ + public void update(int i, int val) { + // As index starts from 0, increment the index by 1 + i += 1; + while (i <= n) { + fen_t[i] += val; + i += i & (-i); + } + } + + /* A function which will return the cumulative sum from index 1 to index i*/ + public int query(int i) { + // As index starts from 0, increment the index by 1 + i += 1; + int cumSum = 0; + while (i > 0) { + cumSum += fen_t[i]; + i -= i & (-i); + } + return cumSum; + } +} \ No newline at end of file