![]() |
VOOZH | about |
Given a height h, count and return the maximum number of balanced binary trees possible with height h. A balanced binary tree is one in which for every node, the difference between heights of left and right subtree is not more than 1.
Examples :
Input : h = 3 Output : 15 Input : h = 4 Output : 315
Following are the balanced binary trees of height 3.
Height of tree, h = 1 + max(left height, right height)
Since the difference between the heights of left and right subtree is not more than one, possible heights of left and right part can be one of the following:
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))
Hence we can see that the problem has optimal substructure property.
A recursive function to count no of balanced binary trees of height h is:
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));
}The time complexity of this recursive approach will be exponential. The recursion tree for the problem with h = 3 looks like :
👁 Image
As we can see, sub-problems are solved repeatedly. Therefore we store the results as we compute them.
An efficient dynamic programming approach will be as follows :
Below is the implementation of above approach:
No. of balanced binary trees of height h is: 15
Time Complexity: O(n)
Auxiliary Space: O(n), since n extra space has been taken.
Memory efficient Dynamic Programming approach :
If we observe carefully, in the previous approach to calculate dp[i] we are using dp[i-1] and dp[i-2] only and dp[0] to dp[i-3] are no longer required. Hence we can replace dp[i],dp[i-1] and dp[i-2] with dp2, dp1 and dp0 respectively. ( contributed by Kadapalla Nithin Kumar)
Implementation:
No. of balanced binary trees of height h is: 15
Time Complexity: O(n)
Auxiliary Space: O(1)
other Geek.