Counting Valid Ordered Binary Trees on n Labeled Nodes
Dynamic ProgrammingAuto-graded · 19 test casesLast updated
Count the distinct binary search trees on keys 1..n by splitting on the root and combining independent subtree counts with dynamic programming.
You are given a positive integer n. Consider the keys 1, 2, ..., n. Determine how many different binary search trees can be formed so that each of these keys appears in exactly one node and no other keys appear.
A binary search tree here follows the usual ordering rule: for any node, every key stored in its left subtree is strictly smaller than the node's key, and every key stored in its right subtree is strictly larger.
Two trees are considered different if their shapes differ. Since the ordering rule forces which key goes in which position of a given shape, counting different trees is the same as counting different shapes.
Return the total number of distinct trees as an integer.
Constraints
1 <= n <= 19- The answer for
n = 19is 1,767,263,190. - Every tree must use all
nkeys exactly once.
Examples
Example 1
Input: num_distinct_bsts(3)
Output: 5
Example 2
Input: num_distinct_bsts(1)
Output: 1
Example 3
Input: num_distinct_bsts(4)
Output: 14
Hints
Hint 1
Try choosing a key k as the root. Which keys are forced into the left subtree, and which into the right?
Hint 2
The number of trees on a group of consecutive keys depends only on how many keys are in the group, not on their actual values. Define dp[m] as the count for m keys.
Hint 3
Left and right subtrees are chosen independently, so multiply their counts; different roots give different trees, so add across roots. Remember that an empty subtree counts as exactly one way (dp[0] = 1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Fix which key is the root. If the root is the k-th smallest of m keys, the ordering rule forces the k-1 smaller keys into the left subtree and the remaining m-k larger keys into the right subtree. The two sides can be built independently, so the number of trees with that root is the product of the number of left shapes and the number of right shapes.
The count of trees depends only on how many keys a subtree holds, not on which values they are. So let dp[m] be the number of distinct BSTs on m consecutive keys. Then:
dp[0] = 1
dp[m] = sum over r = 0..m-1 of dp[r] * dp[m-1-r]
Here r is the size of the left subtree, and the right subtree gets the remaining m-1-r keys. These are the Catalan numbers.
Why it is correct
- Every tree has exactly one root, so each tree falls into exactly one term of the sum (different roots give disjoint sets of trees).
- For a fixed root, any left shape can be combined with any right shape, and different pairs give different trees, so the counts multiply.
dp[0] = 1because there is exactly one empty tree. This ensures that a root at the smallest or largest key contributes1 * dp[m-1]rather than 0.
Check: dp[1] = 1, dp[2] = 2, dp[3] = 2 + 1 + 2 = 5, dp[4] = 5 + 2 + 2 + 5 = 14.
Complexity
- Time: O(n^2), since for each
mwe summproducts. - Space: O(n) for the
dparray.
A closed form also exists: comb(2n, n) // (n + 1), giving O(n) time, but the DP shows the underlying reasoning.
Reference solution
def num_distinct_bsts(n: int) -> int:
# dp[m] = number of distinct BSTs built from m consecutive keys
dp = [1] + [0] * n
for m in range(1, n + 1):
# r keys go left, m - 1 - r keys go right, one key is the root
dp[m] = sum(dp[r] * dp[m - 1 - r] for r in range(m))
return dp[n]