SDE & MLE Prep

96. Unique Binary Search Trees

Problem

Return how many structurally different binary search trees can store the values 1…n.

Example: n = 3 → 5

Constraints: n ≤ 19.

Pick root r: left subtree uses r−1 nodes, right uses n−r. G(n) = Σ G(r−1)·G(n−r) — the Catalan numbers.

Complexity: O(n²).

class Solution:
    def numTrees(self, n: int) -> int:
        G = [1] + [0] * n
        for m in range(1, n + 1):
            G[m] = sum(G[r - 1] * G[m - r] for r in range(1, m + 1))
        return G[n]