progress

~/problems / Counting / Catalan numbers

Unique Binary Search Trees

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

Write num_trees(n: int) -> int returning how many structurally different binary search trees store exactly the keys 1..n.

Constraints: 1 <= n <= 19.

num_trees(1)   # 1
num_trees(3)   # 5
num_trees(4)   # 14

⭐ Bonus: a speed test with n = 19 earns a star in about O(n²). Plain recursion over every tree is far too slow there.

Show hint

Choose the root first. Given the root, which keys go left and which go right, and does anything other than the number of keys on each side matter? That gives a recurrence you can fill as a table.

Topic: Catalan numbers. C(n) = sum C(i) C(n-i-1): trees, parenthesizations.

0:00
Ctrl ' run · Ctrl ↵ submit
esc