Given n values I created a Binary Max-Heap. I want to know the formula to calculate height of subtree rooted at any position i.
3 Answers
Each level in complete binary heap has 2^i nodes , so any binary heap must have 2^i nodes in level (i) except last level.
..............................(100)................... 2^0 nodes
............................./.....\..................
...........................(19)...(36)................ 2^1
........................../...\.../...\...............
.......................(17)..(3).(25).(1)............. 2^2
......................./..\...........................
.....................(2).(7).......................... last level.
because last level may be not complete so n < 2^h
The level of any node at position k
is floor(log2(k + 1))
.
So the height of the subtree rooted at position i
is the difference of levels (assuming that a single leaf has height 0): height = floor(log2(n + 1)) - floor(log2(i + 1))
.
We need to check if the subtree reaches the bottom of the heap or if it is one level shorter. We do this by comparing the left-most leaf to the last element:
if(pow(2, height) * (i + 1) - 1 >= n)
height--;

- 32,049
- 4
- 39
- 70
simple algorithm:- go left till you hit null. this can be done in binary heap by left = 2*parent
. The time complexity of algorithm is O(logn)
. Moreover you can directly evaluate it using following inequality :- 2^k*i < N , k < log2(N/i) , k = log2(floor(N/i))
. The above calculation can be done efficiently in O(log(log(n)))
where you need to do binary search on the highest bit set in floor(N/i)
.
Finding highest bit set in integer :-
high = 63
low = 0
mid = 0
while(low<high) {
mid = (low+high)>>1
val = 1<<mid
if(val==mid)
return mid
if(val>mid) {
high = mid-1
}
else low = mid+1
}
return mid

- 6,106
- 3
- 20
- 19