Consider a Binary Heap of size N. We need to find the height of it.
Examples:
Input : N = 6
Output : 2
()
/ \
() ()
/ \ /
() () ()
Input : N = 9
Output : 3
()
/ \
() ()
/ \ / \
() () () ()
/ \
() ()
Let the size of the heap be N and the height be h. If we take a few examples, we can notice that the value of h in a complete binary tree is floor(log2N).
Examples:
N h
---------
1 0
2 1
3 1
4 2
5 2
.....
.....
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int height( int N)
{
return floor (log2(N));
}
int main()
{
int N = 2;
cout << height(N);
return 0;
}
|
Java
import java.lang.*;
class GFG {
static int height( int N)
{
return ( int )Math.ceil(Math.log(N +
1 ) / Math.log( 2 )) - 1 ;
}
public static void main(String[] args)
{
int N = 6 ;
System.out.println(height(N));
}
}
|
Python 3
import math
def height(N):
return math.ceil(math.log2(N + 1 )) - 1
N = 6
print (height(N))
|
C#
using System;
class GFG {
static int height( int N)
{
return ( int )Math.Ceiling(Math.Log(N
+ 1) / Math.Log(2)) - 1;
}
public static void Main()
{
int N = 6;
Console.Write(height(N));
}
}
|
PHP
<?php
function height( $N )
{
return ceil (log( $N + 1, 2)) - 1;
}
$N = 6;
echo height( $N );
?>
|
Javascript
<script>
function height(N)
{
return Math.ceil(Math.log(N + 1) / Math.log(2)) - 1;
}
let N = 6;
document.write(height(N));
</script>
|
Time Complexity: O(1), Since performing constant operations.
Auxiliary Space: O(1), Since constant extra space is used.