Introduction
The Balanced Binary Tree Counter problem is a Dynamic Programming problem based on Binary Trees.
In this problem, we are given an integer h, representing the height of a binary tree. Our task is to count the number of different balanced binary tree structures that can be formed with that height.
Before solving the problem, let's understand two important concepts.
What Is a Binary Tree?
A Binary Tree is a hierarchical data structure in which each node can have at most two children:
Left child
Right child
What Is a Balanced Binary Tree?
A Balanced Binary Tree is a binary tree in which the difference between the heights of the left and right subtrees of every node is at most 1.
Mathematically:
|Height(Left) - Height(Right)| <= 1For this problem, we consider:
Height of an empty tree = 0
Height of a single-node tree = 1
Our goal is to calculate the number of distinct balanced binary tree structures for a given height h.
Understanding the Problem with Examples
Let's understand the possible balanced binary trees for different heights.
Example 1: Height = 0
An empty tree has exactly one possible structure.
Output: 1Example 2: Height = 1
Only one structure is possible: a single root node.
Output: 1Example 3: Height = 2
Three different structures are possible:
Root with only a left child
Root with only a right child
Root with both left and right children
Output: 3Example 4: Height = 3
For height 3, there are 15 different balanced binary tree structures.
Output: 15These examples show that the number of balanced binary trees increases quickly as the height increases.
Generating every possible tree individually would be inefficient. Instead, we can use Dynamic Programming.
Understanding the Dynamic Programming Approach
Dynamic Programming is a technique in which we solve a larger problem using previously calculated smaller subproblems.
For this problem, we define:
dp[h] = Number of balanced binary trees of height exactly hTo calculate the answer for height h, we need the results for the previous two heights.
Deriving the Recurrence Relation
For a balanced binary tree of height h, at least one subtree must have height h - 1.
There are two possible cases.
Case 1: Both Subtrees Have Height h - 1
The left subtree has height h - 1, and the right subtree also has height h - 1.
The number of combinations is:
dp[h - 1] * dp[h - 1]or:
dp[h - 1]^2Case 2: One Subtree Has Height h - 1 and the Other Has Height h - 2
There are two possible arrangements:
Left subtree has height
h - 1, right subtree has heighth - 2Left subtree has height
h - 2, right subtree has heighth - 1
The number of combinations is:
2 * dp[h - 1] * dp[h - 2]Combining both cases, we get the recurrence relation:
dp[h] = dp[h - 1]^2 + 2 * dp[h - 1] * dp[h - 2]This is the main formula used to solve the problem.
Base Conditions
Before calculating the recurrence, we need two initial values.
Height | Number of Balanced Trees |
|---|---|
0 | 1 |
1 | 1 |
Why Is dp[0] = 1?
An empty tree is considered one valid structure. This helps us correctly calculate combinations for larger heights.
Why Is dp[1] = 1?
A tree with height 1 contains only one root node.
Therefore:
dp[0] = 1;
dp[1] = 1;Java Implementation
Let's implement the solution using an optimized Dynamic Programming approach.
class Solution {
public int countBT(int h) {
int mod = 1000000007;
// Base conditions
if (h == 0) return 1;
if (h == 1) return 1;
// Previous two results
long a = 1; // Height 0
long b = 1; // Height 1
// Calculate results from height 2 to h
for (int i = 2; i <= h; i++) {
// Apply recurrence relation
long c = (b * b + 2 * b * a) % mod;
// Update previous values
a = b;
b = c;
}
return (int) b;
}
}Line-by-Line Code Explanation
Let's understand how the implementation works.
Step 1: Declare the Modulo Value
int mod = 1000000007;The number of possible balanced binary trees increases rapidly.
Therefore, the problem requires us to return the answer modulo 10^9 + 7.
Step 2: Handle Base Conditions
if (h == 0) return 1;
if (h == 1) return 1;For height 0 and height 1, the answer is already known.
We can return the result directly without executing the loop.
Step 3: Initialize Previous Results
long a = 1;
long b = 1;Here:
astores the result for heighti - 2bstores the result for heighti - 1
Initially, they represent heights 0 and 1.
Step 4: Execute the Loop
for (int i = 2; i <= h; i++)We start from height 2 because the answers for heights 0 and 1 are already available.
The loop continues until we reach the required height.
Step 5: Calculate the Current Result
long c = (b * b + 2 * b * a) % mod;This statement implements our recurrence relation:
dp[h] = dp[h - 1]^2 + 2 * dp[h - 1] * dp[h - 2]Here, c stores the number of balanced binary trees for the current height.
Step 6: Update Previous Results
a = b;
b = c;After calculating the current result, we shift the previous values.
areceives the previous value ofbbreceives the newly calculated value ofc
This allows us to calculate the next height without using an additional DP array.
Step 7: Return the Result
return (int) b;After the loop finishes, b contains the answer for the given height.
We convert it to an integer and return it.
Dry Run: Example with h = 3
Let's execute the algorithm step by step.
Input:
h = 3Initial values:
a = 1
b = 1Iteration 1: i = 2
Apply the recurrence relation:
c = b^2 + 2 * b * aSubstitute the values:
c = 1^2 + 2 * 1 * 1Therefore:
c = 1 + 2
c = 3Update the variables:
a = 1
b = 3Iteration 2: i = 3
Current values:
a = 1
b = 3Apply the formula:
c = 3^2 + 2 * 3 * 1Therefore:
c = 9 + 6
c = 15Update:
a = 3
b = 15Finally:
return 15;Output:
15Complete Dry Run Table
Iteration | a | b | c |
|---|---|---|---|
Initial | 1 | 1 | - |
i = 2 | 1 | 1 | 3 |
i = 3 | 1 | 3 | 15 |
After the final iteration, b = 15, so the answer is:
15Why Do We Use Modulo 10^9 + 7?
The number of balanced binary tree structures grows very quickly as the height increases.
To prevent the answer from becoming too large, the problem requires modulo:
10^9 + 7 = 1000000007In Java:
long c = (b * b + 2 * b * a) % mod;We use long instead of int because multiplication can produce values larger than the range supported by a Java int.
Using long provides enough range for the intermediate calculations in this recurrence with the given modulo.
Time and Space Complexity
Time Complexity: O(h)
The loop executes from 2 to h.
Therefore, the total number of iterations is proportional to the given height.
O(h)Auxiliary Space Complexity: O(1)
We only use three variables:
abc
We do not create an additional DP array.
Therefore, the auxiliary space complexity is:
O(1)This is an example of space optimization in Dynamic Programming.
Common Mistakes
When solving this problem, a few implementation details are easy to overlook.
Using int for Intermediate Multiplication
Avoid performing the multiplication using int variables because the values can exceed the range of a Java int.
Using long for a, b, and c avoids this issue.
Forgetting the Modulo Operation
The number of possible tree structures grows very quickly. If the modulo operation is not applied during every iteration, the values can become too large.
Apply the modulo while calculating the current result:
long c = (b * b + 2 * b * a) % mod;Using Incorrect Base Values
The recurrence depends on both dp[0] and dp[1].
Using:
dp[0] = 1
dp[1] = 1ensures that the recurrence produces the correct results for subsequent heights.
Conclusion
The Balanced Binary Tree Counter problem demonstrates how Dynamic Programming can simplify a tree-counting problem.
Instead of generating every possible binary tree, we derive a recurrence relation and calculate the answer using the previous two results.
The optimized implementation provides:
Time Complexity: O(h)
Auxiliary Space Complexity: O(1)
The key idea is to recognize the two possible combinations of subtree heights:
Both subtrees have height
h - 1One subtree has height
h - 1and the other has heighth - 2
These two cases lead to the recurrence:
dp[h] = dp[h - 1]^2 + 2 * dp[h - 1] * dp[h - 2]Understanding this pattern is useful for other Dynamic Programming problems where the number of possible tree structures must be calculated without explicitly generating every tree.


Join the conversation! Your thoughts help the community grow.