Binary Indexed Tree

​
node count
nodes
20
query range
start
1
end
20
drawing mode
mode
layered
radial
operations: 2
sum of interval [1,20]: 86
index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
value
7
5
6
3
6
5
5
8
2
2
5
4
5
3
3
2
3
4
7
1
tree
7
12
6
21
6
11
5
45
2
4
5
13
5
8
3
71
3
7
7
15
This Demonstration implements a binary indexed tree (also known as a Fenwick tree), a data structure used mainly to calculate prefix sums (or sums of ranges) in a list efficiently. To compute the sum of the values in a range of the list, move the start and end sliders to specify it. Hover over the entries in the "tree" row to see which elements in the list are contained in that node.
The prefix sum of a list in a certain index is the sum of all of the elements in the list up to and including that index. This algorithm speeds up the computation of prefix sums when the list's items can change; there are more efficient algorithms to compute prefix sums of static lists.
Green nodes represent the values that are added to compute the answer, while red nodes represent the values that are subtracted. Olive-colored nodes are added and subtracted as part of the algorithm, but they do not affect the answer.

Details

Each node stores the sum of the interval
[parent,node]
in the original list, so by starting at any node and adding up the values of all of the nodes on the way to the root, the sum of the interval
[1,node]
(its prefix sum) is computed. With this, to compute the sum of any given interval
[m,n]
, it is only necessary to compute
sum[1,n]-sum[1,m-1]
.
The tree is "binary indexed" because the parent of each node is obtained by setting to 0 the least significant bit that is 1 from the node's index in base 2.
Queries can be executed with
O(logN)
time complexity after a one-time precomputation step that takes
O(NlogN)
. If the array is modified, the tree can be updated in
O(logN)
time for each modified position.

Permanent Citation

Freddy Román
​
​"Binary Indexed Tree"​
​http://demonstrations.wolfram.com/BinaryIndexedTree/​
​Wolfram Demonstrations Project​
​Published: September 27, 2012