What happens here if you have an array of n elements, then the segment tree will have a node leaf for each of these n records. Thus, we have (n) leaf nodes, as well as (n-1) inner nodes.
The total number of nodes = n + (n-1) = 2n-1 Now we know its complete binary tree and, therefore, the height: ceil (Log2 (n)) +1
Total No. nodes = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... + 2 ^ ceil (Log2 (n)) // which is a geometric progression, where 2 ^ i denotes the number of nodes at level i.
The summation formula GP = a * (r ^ size - 1) / (r-1) where a = 2 ^ 0
Total No. nodes = 1 * (2 ^ (ceil (Log2 (n)) + 1) -1) / (2-1)
= 2 * [2 ^ ceil (Log2 (n))] -1 (you need space in the array for each of the internal as well as leaf nodes that are this number in number), so this is an array size.
= O (4 * n) approximately ...
You may also think so, this is a tree of segments:
10 / \ 3 7 /\ /\ 1 2 3 4
If you are a segment tree above, then the array of segments array will be: 10,3,7,1,2,3,4, that is, the 0th element will store the sum of the 1st and 2nd records, the 1st record will be store the amount of 3, 4 and 2 will store the amount of the 5th and 6th records!
In addition, the best explanation: if the size of the array n is 2, then we have exactly n-1 internal nodes, adding up to 2n-1 . But we do not always have n as power 2, so we need the smallest degree n , which is greater than n . It means that
int s=1; for(; s<n; s<<=1);
You can see my answer here.