Given a binary tree organised as in the diagram below (a static tree represented by an array of 15 nodes), I am writing code to compute the interval represented by a given node at index i, given the interval of the entire tree (node 0)? My motivation to do this is to get rid of the need to store the interval in a node instance.
Here's my stab at computing the value. It appears to be correct but I'm wondering if there's a much smarter way of calculating it:
int Log2i(int x)
{
auto r = 0;
while (x >>= 1)
{
++r;
}
return r;
}
void Interval(int i, int min, int max, int & a, int & b)
{
auto d = Log2i(i); // Depth of node i.
auto k = 1 << d; // At this level, there are k intervals.
auto s = max - min; // Total span over which we're partitioned.
auto p = s / k; // Therefore, size of each interval.
auto f = k - 1; // Index of first node for this partition.
a = min + (p * (i - f));
b = a + p;
}
int main(void)
{
auto a = int(), b = int();
Interval(6, 1000, 2000, a, b);
return 0;
}