考虑一个大小为 N 的二叉堆。我们需要找到它的高度。
例子 :
Input : N = 6
Output : 2
()
/ \
() ()
/ \ /
() () ()
Input : N = 9
Output :
()
/ \
() ()
/ \ / \
() () () ()
/ \
() ()
设堆的大小为N ,高度为h
如果我们举几个例子,我们可以注意到,完全二叉树中 h 的值是 ceil(log 2 (N+1)) – 1。
例子 :
N h
---------
1 0
2 1
3 1
4 2
5 2
.....
.....
C++
// CPP program to find height of complete
// binary tree from total nodes.
#include
using namespace std;
int height(int N)
{
return ceil(log2(N + 1)) - 1;
}
// driver node
int main()
{
int N = 6;
cout << height(N);
return 0;
}
Java
// Java program to find height
// of complete binary tree
// from total nodes.
import java.lang.*;
class GFG {
// Function to calculate height
static int height(int N)
{
return (int)Math.ceil(Math.log(N +
1) / Math.log(2)) - 1;
}
// Driver Code
public static void main(String[] args)
{
int N = 6;
System.out.println(height(N));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python 3
# Python 3 program to find
# height of complete binary
# tree from total nodes.
import math
def height(N):
return math.ceil(math.log2(N + 1)) - 1
# driver node
N = 6
print(height(N))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to find height
// of complete binary tree
// from total nodes.
using System;
class GFG {
static int height(int N)
{
return (int)Math.Ceiling(Math.Log(N
+ 1) / Math.Log(2)) - 1;
}
// Driver node
public static void Main()
{
int N = 6;
Console.Write(height(N));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
PHP
Javascript
输出 :
2
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。