给定高度h,计算并返回高度h可能达到的平衡二叉树的最大数量。平衡二叉树是其中每个节点左右子树的高度之差不大于1。
例子 :
Input : h = 3
Output : 15
Input : h = 4
Output : 315
以下是高度为3的平衡二叉树。
树的高度,h = 1 + max(左高度,右高度)
由于左右子树的高度之差不超过一,因此左右部分的可能高度可以是以下之一:
- (h-1),(h-2)
- (h-2),(h-1)
- (h-1),(h-1)
count(h) = count(h-1) * count(h-2) +
count(h-2) * count(h-1) +
count(h-1) * count(h-1)
= 2 * count(h-1) * count(h-2) +
count(h-1) * count(h-1)
= count(h-1) * (2*count(h - 2) +
count(h - 1))
因此,我们可以看到该问题具有最佳的子结构属性。
一个不计算高度为h的平衡二叉树的递归函数为:
int countBT(int h)
{
// One tree is possible with height 0 or 1
if (h == 0 || h == 1)
return 1;
return countBT(h-1) * (2 *countBT(h-2) +
countBT(h-1));
}
这种递归方法的时间复杂度将是指数级的。 h = 3的问题的递归树如下所示:
如我们所见,子问题可以反复解决。因此,我们在计算结果时会存储它们。
一种有效的动态编程方法如下:
下面是上述方法的实现:
C++
// C++ program to count number of balanced
// binary trees of height h.
#include
#define mod 1000000007
using namespace std;
long long int countBT(int h) {
long long int dp[h + 1];
//base cases
dp[0] = dp[1] = 1;
for(int i = 2; i <= h; i++) {
dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%mod + dp[i - 1])%mod) % mod;
}
return dp[h];
}
// Driver program
int main()
{
int h = 3;
cout << "No. of balanced binary trees"
" of height h is: "
<< countBT(h) << endl;
}
Java
// Java program to count number of balanced
// binary trees of height h.
class GFG {
static final int MOD = 1000000007;
public static long countBT(int h) {
long[] dp = new long[h + 1];
// base cases
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= h; ++i)
dp[i] = (dp[i - 1] * ((2 * dp [i - 2])% MOD + dp[i - 1]) % MOD) % MOD;
return dp[h];
}
// Driver program
public static void main (String[] args) {
int h = 3;
System.out.println("No. of balanced binary trees of height "+h+" is: "+countBT(h));
}
}
/*
This code is contributed by
Brij Raj Kishore
*/
Python3
# Python3 program to count number of balanced
# binary trees of height h.
def countBT(h) :
MOD = 1000000007
#initialize list
dp = [0 for i in range(h + 1)]
#base cases
dp[0] = 1
dp[1] = 1
for i in range(2, h + 1) :
dp[i] = (dp[i - 1] * ((2 * dp [i - 2])%MOD + dp[i - 1])%MOD) % MOD
return dp[h]
#Driver program
h = 3
print("No. of balanced binary trees of height "+str(h)+" is: "+str(countBT(h)))
# This code is contributed by
# Brij Raj Kishore
C#
// C# program to count number of balanced
// binary trees of height h.
using System;
class GFG {
static int MOD = 1000000007;
public static long countBT(int h) {
long[] dp = new long[h + 1];
// base cases
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= h; ++i)
dp[i] = (dp[i - 1] * ((2 * dp [i - 2])% MOD + dp[i - 1]) % MOD) % MOD;
return dp[h];
}
// Driver program
static void Main () {
int h = 3;
Console.WriteLine("No. of balanced binary trees of height "+h+" is: "+countBT(h));
}
// This code is contributed by Ryuga
}
PHP
输出 :
No of balanced binary trees of height h is: 15