Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 1 Jul, 2021

Moderate

```
Input:
H = 2
Output:
3
There will be a total 3 different balanced binary trees with height 2.
One node as a root and other nodes on one of the two sides.
One with root and left subtree with one more node than right.
One with root and right subtree with one more node than left.
```

```
The first line contains a single integer 'T' denoting the number of test cases to be run. Then the test cases follow.
Each test case contains a single integer 'H' denoting the height of the tree.
```

```
For each test case, print an integer denoting the number of balanced binary trees that can be made with a given height.
Answers for each test case will be printed in a separate line.
```

```
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
```

```
1 <= T <= 50
1 <= H <= 10^6
Time Limit: 1 sec.
```

As given in the problem, the difference between the heights of the left subtree and right subtree is less than or equal to one, so the heights of the left and the right part will be one of the following:

- (H-1), (H-2)
- (H-2), (H-1)
- (H-1), (H-1)

Hence, we can write the below relation on this.

Say, **CTR(H)** be the no of ways to make a balanced binary tree of height 'H'.

So, by combinatorics, we can write.

CTR(H) = CTR(H-1) * CTR(H-2) +

CTR(H-2) * CTR(H-1) +

CTR(H-1) * CTR(H-1)

= 2 * CTR(H-1) * CTR(H-2) +

CTR(H-1) * CTR(H-1)

= CTR(H-1) * (2*CTR(H - 2) +

CTR(H - 1))

Here, we can see this problem has optimal substructure properties; hence we can use simple recursion to calculate the above equation.

- Make a recursive function
**get()** **get(h)**will give the no of ways to make a balanced binary tree of height h.- inside get function to write the base case of recursion when
**h**is zero or 1 return answer as 1. - if
**h**is not 0 or 1 then return the**get(h-1)*(2*get(h-2)+get(h-1))**. - call
**get()**function for given input height and return the result modulo**1e9+7**.

From the recursive approach, we are calculating the below equation.

CTR(H) = CTR(H-1) * CTR(H-2) +

CTR(H-2) * CTR(H-1) +

CTR(H-1) * CTR(H-1)

= 2 * CTR(H-1) * CTR(H-2) +

CTR(H-1) * CTR(H-1)

= CTR(H-1) * (2*CTR(H - 2) +

CTR(H - 1))

In the above equation, as we can see, we are calculating some values again and again like we are calling CTR(H-1) two times there and the same with all values. Using dynamic programming, we can pre calculate all values, which can be used to generate the above equation effectively.

- Initialize the dp array of size h+1
- Initialize mod as 1e9+7 we will use this to avoid overflow and return the answer after taking modulo with it.
- Make dp[0] and dp[1] equal to 1. this are base cases
- Run a loop from 2 to h+1 and update each of the dp states.
- Make dp[i] = (dp[i-1] * (2* dp[i-2]%mod + dp[i-1]%mod)%mod.
- Return the dp[h].