1
1
# Fenwick Tree / Binary Indexed Tree
2
2
3
- A simple data structure that supports fast range queries
4
- in an array. However, it is usually only valid for reversible
5
- operations, like addition and subtraction
3
+ A ** Fenwick tree** or ** binary indexed tree** is a data
4
+ structure that can efficiently update elements and
5
+ calculate prefix sums in a table of numbers.
6
+
7
+ When compared with a flat array of numbers, the Fenwick tree achieves a
8
+ much better balance between two operations: element update and prefix sum
9
+ calculation. In a flat array of ` n ` numbers, you can either store the elements,
10
+ or the prefix sums. In the first case, computing prefix sums requires linear
11
+ time; in the second case, updating the array elements requires linear time
12
+ (in both cases, the other operation can be performed in constant time).
13
+ Fenwick trees allow both operations to be performed in ` O(log n) ` time.
14
+ This is achieved by representing the numbers as a tree, where the value of
15
+ each node is the sum of the numbers in that subtree. The tree structure allows
16
+ operations to be performed using only ` O(log n) ` node accesses.
17
+
18
+ ## Implementation Notes
6
19
7
20
Binary Indexed Tree is represented as an array. Each node of Binary Indexed Tree
8
21
stores sum of some elements of given array. Size of Binary Indexed Tree is equal
@@ -11,6 +24,12 @@ size as `n+1` for ease of implementation. All the indexes are 1-based.
11
24
12
25
![ Binary Indexed Tree] ( https://www.geeksforgeeks.org/wp-content/uploads/BITSum.png )
13
26
27
+ On the picture below you may see animated example of
28
+ creation of binary indexed tree for the
29
+ array ` [1, 2, 3, 4, 5] ` by inserting one by one.
30
+
31
+ ![ Fenwick Tree] ( https://upload.wikimedia.org/wikipedia/commons/d/dc/BITDemo.gif )
32
+
14
33
## References
15
34
16
35
- [ Wikipedia] ( https://en.wikipedia.org/wiki/Fenwick_tree )
0 commit comments