KatInterview

Counting Valid Ordered Binary Trees on n Labeled Nodes

Dynamic ProgrammingAuto-graded · 19 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingcombinatoricsbinary-search-tree

Last 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 = 19 is 1,767,263,190.
  • Every tree must use all n keys 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).