Skip to content
BytePatterns

Unique BST Shapes

MediumDynamic Programming#bottom-up-dp#counting~30m

Problem

Count the structurally different binary search trees that can hold the values 1 through n, each value used exactly once. Two trees differ when their shapes differ, so the same values arranged differently count separately. For n equal to 0 the answer counts the single empty tree.

Examples

Input:  n = 3
Output: 5
Why:    each of the three values can be the root, and the root 2 allows only one shape
Input:  n = 1
Output: 1
Why:    a single value has exactly one tree
Input:  n = 0
Output: 1
Why:    edge case, the empty tree is one valid shape

Hints

0 / 3

Stuck on the idea rather than the code? BST Basics covers it.