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:

  1. Left child

  2. 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:

Code
|Height(Left) - Height(Right)| <= 1

For 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.

Code
Output: 1

Example 2: Height = 1

Only one structure is possible: a single root node.

Code
Output: 1

Example 3: Height = 2

Three different structures are possible:

  1. Root with only a left child

  2. Root with only a right child

  3. Root with both left and right children

Code
Output: 3

Example 4: Height = 3

For height 3, there are 15 different balanced binary tree structures.

Code
Output: 15

These 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:

Code
dp[h] = Number of balanced binary trees of height exactly h

To 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:

Code
dp[h - 1] * dp[h - 1]

or:

Code
dp[h - 1]^2

Case 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 height h - 2

  • Left subtree has height h - 2, right subtree has height h - 1

The number of combinations is:

Code
2 * dp[h - 1] * dp[h - 2]

Combining both cases, we get the recurrence relation:

Code
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:

Code
dp[0] = 1;
dp[1] = 1;

Java Implementation

Let's implement the solution using an optimized Dynamic Programming approach.

C#
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

Code
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

Code
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

Code
long a = 1;
long b = 1;

Here:

  • a stores the result for height i - 2

  • b stores the result for height i - 1

Initially, they represent heights 0 and 1.

Step 4: Execute the Loop

Code
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

Code
long c = (b * b + 2 * b * a) % mod;

This statement implements our recurrence relation:

Code
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

Code
a = b;
b = c;

After calculating the current result, we shift the previous values.

  • a receives the previous value of b

  • b receives the newly calculated value of c

This allows us to calculate the next height without using an additional DP array.

Step 7: Return the Result

Code
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:

Code
h = 3

Initial values:

Code
a = 1
b = 1

Iteration 1: i = 2

Apply the recurrence relation:

Code
c = b^2 + 2 * b * a

Substitute the values:

Code
c = 1^2 + 2 * 1 * 1

Therefore:

Code
c = 1 + 2
c = 3

Update the variables:

Code
a = 1
b = 3

Iteration 2: i = 3

Current values:

Code
a = 1
b = 3

Apply the formula:

Code
c = 3^2 + 2 * 3 * 1

Therefore:

Code
c = 9 + 6
c = 15

Update:

Code
a = 3
b = 15

Finally:

Code
return 15;

Output:

Code
15

Complete 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:

Code
15

Why 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:

Code
10^9 + 7 = 1000000007

In Java:

Code
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.

Code
O(h)

Auxiliary Space Complexity: O(1)

We only use three variables:

  • a

  • b

  • c

We do not create an additional DP array.

Therefore, the auxiliary space complexity is:

Code
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:

Code
long c = (b * b + 2 * b * a) % mod;

Using Incorrect Base Values

The recurrence depends on both dp[0] and dp[1].

Using:

Code
dp[0] = 1
dp[1] = 1

ensures 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:

  1. Both subtrees have height h - 1

  2. One subtree has height h - 1 and the other has height h - 2

These two cases lead to the recurrence:

Code
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.