Height of a complete binary tree (or Heap) with N nodes

Last Updated : 4 Feb, 2026

Consider a Binary Heap of size N. Determine the height of the heap.

Examples:

Input : N = 6

tree

Output : 2
Explanation: The height of a tree is the number of edges on the longest path from root to leaf. Here, the longest path (e.g., 1 - 3 - 5) has 2 edges, so the tree’s height is 2.

Input : N = 9

ttree

Output : 3
Explanation: In this tree the longest path (e.g., 2 - 3 - 5 - 6) has 3 edges, so the tree’s height is 3.

Try it on GfG Practice
redirect icon

[Approach] Using Mathematical Formula - O(1) Time and O(1) Space

Since a binary heap is a complete binary tree, its height is found using the formula floor(log2N).

C++
#include <iostream>
using namespace std;

int height(int N)
{
    return floor(log2(N));
}

int main()
{
    int N = 6;
    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
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));
    }
}
JavaScript
function height(N)
{
    return Math.ceil(Math.log(N + 1) / Math.log(2)) - 1;
}
    
// Driver Code    
let N = 6;
console.log(height(N));

Output
2
Comment