What is a binary indexed tree?
A binary indexed tree is used to efficiently answer prefix sum queries. It takes space, where is the size of the input array.
Construction
Take a look at the important facts below:
- The binary indexed tree will take nodes.
- Each binary tree node contains an index and a value. The value is a prefix sum.
The following illustration explains how a binary indexed tree is created. An indexed binary tree can be represented as an array or a tree. For simplicity, we will represent it as a tree.
To obtain the parent of a node with index i:
- Covert i to binary.
- Flip the rightmost bit containing 1 to 0.
For all nodes with an index greater than zero:
- Express the index in terms of the sum of powers of 2.
- The first element in the expression denotes the index in the original array from which we need to start computing the sum.
- The last element in the expression denotes the number of input array elements that need to be included.
Update
If there is a change made at index of the input array, then the binary indexed tree needs to be updated. Suppose that is added to the value at in the input array. To update the binary indexed tree, go to index :
-
Go to the index in the binary indexed tree. Add to the value in this node.
-
Find the next index to update in the indexed binary tree by finding current index + (current index & (-current index)). Add to the value in this node and repeat this step until the new index is greater than the number of nodes in the indexed binary tree.
Obtaining the prefix sum
To find the sum of a prefix from to :
- Let answer = 0. Go to the index in the binary indexed tree.
- Traverse from this node to its parent node and add this value to the variable answer.
- Keep traversing until you reach the parent node and keep adding the values (to the variable answer) in the nodes encountered.
The following illustration shows how to obtain a prefix sum from index to of the input array.
Free Resources