Find what row a given number exists in within a binary heap tree.

45 Views Asked by At

If I have a binary heap tree like so:

            1
     2,             3
 4,     5,      6,      7
8, 9, 10, 11, 12, 13, 14, 15
16 ... 31
32 ... 63
64 ... 127

I would say 5 is in row 3, and 115 is in row 7.

I'm sure the equation is stupid simple like "duh, find the square root." But I'm not seeing it.

So how do I determine which row in the heap a given number is in.

1

There are 1 best solutions below

4
On BEST ANSWER

Oh ok, gotcha.

number $n$ is going to be in the following level:

$\lfloor \log_2(n) \rfloor +1$

Here is a c++ function for it:

int findfloor(int x){
    int i,j;
    for(i=0,j=1; 2*j <= x; i++,j*=2){}
    return(i+1);
}