Count Balanced Binary Trees of Height h
Pattern: DP on trees
A balanced tree of height h has subtrees of heights (h-1, h-1), (h-1, h-2) or (h-2, h-1). So count(h) = count(h-1)² + 2 × count(h-1) × count(h-2).
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return the number of balanced binary trees (at every node, the two subtree heights differ by at most 1) of height h, where a single node has height 1. The answer is taken modulo 10⁹ + 7.
Think first
- What heights can the root's subtrees have?
- How are the counts combined?
- Why does it grow so fast?
Hints
Brute force, and why it fails
Build every tree shape: astronomically many.
The key insight
The count for height h depends only on the counts for h - 1 and h - 2.
Dry run
| c | 1 1 |
|---|
Heights 0 and 1 each have one tree here.
Step 1 of 2
The plan
a, b = 1, 1
for k in 2..h: a, b = b, (b × b + 2 × b × a) mod M
return b
Complexity
- Time
O(h)- Space
O(1)
Two numbers carried.
Edge cases
- h = 1: 1.
- h = 2: 3.
- Large h: modulo.
I've built my logic, show the code
Java
class Solution {
public int countBT(int h) {
final long MOD = 1_000_000_007L;
long prev = 1, cur = 1; // trees of height h - 2 and h - 1 (heights 0 and 1 both have one)
for (int k = 2; k <= h; k++) { // subtrees of heights (k-1, k-1), (k-1, k-2) or (k-2, k-1)
long next = (cur * cur % MOD + 2 * cur % MOD * prev % MOD) % MOD;
prev = cur;
cur = next;
}
return (int) cur;
}
}C++
class Solution {
public:
int countBT(int h) {
const long long MOD = 1000000007LL;
long long prev = 1, cur = 1; // trees of height h - 2 and h - 1 (heights 0 and 1 both have one)
for (int k = 2; k <= h; k++) { // subtrees of heights (k-1, k-1), (k-1, k-2) or (k-2, k-1)
long long next = (cur * cur % MOD + 2 * cur % MOD * prev % MOD) % MOD;
prev = cur;
cur = next;
}
return static_cast<int>(cur);
}
};Python
class Solution:
def countBT(self, h: int) -> int:
MOD = 1_000_000_007
prev = cur = 1 # trees of height h - 2 and h - 1 (heights 0 and 1 both have one)
for _ in range(2, h + 1): # subtrees of heights (k-1, k-1), (k-1, k-2) or (k-2, k-1)
prev, cur = cur, (cur * cur + 2 * cur * prev) % MOD
return curCommon mistakes
- Forgetting the factor 2.
- Overflow before the modulo.