Balanced Binary Tree

You are given an integer 'H'. Your task is to count and print the maximum number of balanced binary trees possible with height 'H'.

The balanced binary tree is one in which, for every node, the difference between the left and right subtree heights is less than or equal to 1.

You have to print the answer with modulo 1e9+7.

For Example:
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. 
Input Format:
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. 
Output Format:
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.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
Constraints:
1 <= T <= 50
1 <= H <= 10^6

Time Limit: 1 sec.
AnswerBot
1y

The maximum number of balanced binary trees possible with a given height is to be counted and printed.

  • A balanced binary tree is one in which the difference between the left and right subtree heights i...read more

CodingNinjas
author
2y

I used postorder tee traversal to solve this problem, first go on left subtree and return the height, similarly gets height of right subtree and check if absolute difference is less than or equal to 1...read more

CodingNinjas
author
2y
Recursion.

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 t...read more

CodingNinjas
author
2y
Dynamic Programming.

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)...read more

Add answer anonymously...
Josh Technology Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter