Height of a complete Binary tree or Binary heap with N Nodes

Complete Binary Tree:

A complete binary tree is a binary tree in which all the levels are completely filled except the last level and the last level must be filled from the left.

Properties of Complete binary tree:

In a complete binary tree all the leaves are at the same level.
The height of the complete binary tree with n nodes is log(n+1).

The above example is the complete binary tree in which all the levels are completely filled.

Complete Binary tree:

A Binary tree is said to be a complete binary tree if all the levels of the tree are completely filled except the last level where all the nodes are as left as possible.

#include <bits/stdc++.h>
using namespace std;
 
int height(int N)
{
    return floor(log2(N));
}
 
// driver node
int main()
{
    int N = 6;
    cout << height(N);
    return 0;
}


import java.lang.*;
 
class prepbytes {
     
    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));
    }
}

 
import math
def height(N):
    return math.ceil(math.log2(N + 1)) - 1
 
# driver node
N = 6
print(height(N))

This article tried to find the Height of a complete Binary tree or Binary heap with N Nodes. Hope this blog helps you understand the concept. To practice problems on Heap you can check out MYCODE | Competitive Programming – Heaps.

Leave a Reply

Your email address will not be published. Required fields are marked *