Unique Binary Search Trees (LeetCode 96): Solution and Explanation

Medium
Math
Dynamic Programming
Tree
Binary Search Tree
Binary Tree

Given n, count the structurally different binary search trees that hold exactly the values 1 to n. Only the shape of the tree matters, since the BST rule then fixes where every value goes.

Intuition

Pick the root first. Once value j is the root, the BST rule leaves no choice about where the other values go: everything smaller than j lives in the left subtree and everything larger lives in the right subtree.

The two subtrees are independent. Any valid left subtree can sit next to any valid right subtree, so root j produces (number of trees on the left keys) times (number of trees on the right keys) trees.

The count of trees on a group of keys depends only on how many keys there are. Keys 4, 5, 6 form exactly as many BSTs as keys 1, 2, 3. So one array G[k], the number of trees on k keys, covers every subproblem.

Putting it together, G[i] is the sum over every root j of G[j - 1] times G[i - j]. Every term uses smaller sizes, so filling G from 0 upward works. The empty tree counts as one shape, G[0] = 1, so a root with nothing on one side still multiplies correctly.

Approach: Bottom-up Catalan DP

  1. Create G of length n + 1 filled with 0 and set G[0] = 1.
  2. For each size i from 1 to n, loop over every root j from 1 to i.
  3. Add G[j - 1] * G[i - j] to G[i]: left subtree shapes times right subtree shapes.
  4. Return G[n].

Step-by-step example

n = 3
  1. G[0] = 1.
  2. i = 1: root 1 has empty subtrees on both sides, 1 × 1 = 1. G[1] = 1.
  3. i = 2: root 1 gives G[0] × G[1] = 1, root 2 gives G[1] × G[0] = 1. G[2] = 2.
  4. i = 3, root 1: left is empty (1), right holds keys 2..3 (G[2] = 2), so 2 trees.
  5. i = 3, root 2: left holds key 1 and right holds key 3, 1 × 1 = 1 tree. Running total 3.
  6. i = 3, root 3: left holds keys 1..2 (2 shapes), right is empty, 2 trees. G[3] = 5.

Code: Python, Java, C++

1class Solution:
2    def numTrees(self, n: int) -> int:
3        G = [0] * (n + 1)
4        G[0] = 1
5        for i in range(1, n + 1):
6            for j in range(1, i + 1):
7                G[i] += G[j - 1] * G[i - j]
8        return G[n]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

For each size i the inner loop tries i roots, which is 1 + 2 + ... + n = O(n^2) multiplications.

Space

O(n)

Only the array G of length n + 1 is stored.

Other approaches

Closed-form Catalan number (time O(n), space O(1))

G[n] is the n-th Catalan number, C(2n, n) / (n + 1). It can be computed iteratively as C = C * 2(2i + 1) / (i + 2) in O(n), but the formula hides the reasoning and needs care with integer division order.

Memoized recursion (time O(n^2), space O(n))

count(k) = sum of count(j - 1) * count(k - j), cached by k. It is the same recurrence written top-down.

Common mistakes

  • Setting G[0] = 0. The empty subtree is one valid shape, and a 0 there wipes out every root at the edge of the range.
  • Tracking actual key ranges (lo, hi) as the DP state. It works but uses O(n^2) memory for no gain, since only the size of the range matters.
  • Using the closed-form formula with factorials in fixed-width integers. 38! overflows 64 bits long before n reaches 19.

Frequently asked questions

Why does the number of trees depend only on the number of keys?

A BST only compares keys with each other. Relabeling sorted keys 4, 5, 6 as 1, 2, 3 keeps every comparison the same, so the set of valid shapes is identical.

Why multiply instead of add the left and right counts?

Each left subtree can be combined with each right subtree to form a different tree, so the choices pair up. Pairing a options with b options gives a × b combinations.

Does the answer fit in a 32-bit int?

Yes for n up to 19: G[19] = 1,767,263,190, just under 2^31. Every term and partial sum is at most G[i], so no intermediate value overflows either.

How is this related to Unique Binary Search Trees II?

Problem II asks you to build every tree, not just count them. It uses the same split-by-root idea but returns lists of trees, so its output size grows like the Catalan numbers.