LeetCode #96 Medium

Unique Binary Search Trees

Unique Binary Search Trees is LeetCode 96 (Medium). Given n, return how many structurally different binary search trees can hold the values 1 to n, each exactly once.

  • Only the count is needed, not the trees themselves.
  • n is at most 19, and the answer for 19 is 1,767,263,190, which still fits in a 32-bit int.
Constraints
  • 1 <= n <= 19
mathdynamic-programmingtreebinary-search-tree
Open on LeetCode ↗
02

Intuition

Pick the root first. If the root is r, the BST rule forces the values 1 to r − 1 into the left subtree and r + 1 to n into the right one. The two sides are independent, so the trees with root r number (ways to arrange r − 1 nodes) × (ways to arrange n − r nodes).

  • Only the size matters: the values 4, 5, 6 can form exactly as many BSTs as 1, 2, 3, because a BST's shape depends only on the order of its values.
  • Different roots never overlap: two trees with different roots are different trees, so the counts for each root just add.

Let dp[k] be the number of BSTs on k nodes. Then dp[k] is the sum over every root of dp[left size] × dp[right size], and building it from small k up means both factors are always ready.

How to spot this pattern

Counting the shapes of something that splits into two independent halves around a chosen pivot is a Catalan-style DP: sum over every pivot of (ways on the left) × (ways on the right). Generate Parentheses and counting full binary trees follow the same recurrence.

03

Approach

Try it first

Before reading on, fix the root of a 3-node tree to 1, then 2, then 3. How many nodes end up on each side, and how many trees does each choice allow? Add them up and check you get 5.

1

Count the empty tree as one

Set dp[0] = 1. A root with nothing on one side still makes exactly one tree on that side, the empty one; with dp[0] = 0, every product with an empty side would wipe out valid trees.

2

Build counts for 1 node, 2 nodes, up to n

For each size nodes from 1 to n, compute dp[nodes] from smaller sizes only. Every subtree of a tree with nodes nodes is smaller, so its count is already in the table.

3

Try every root and multiply the two sides

For each root from 1 to nodes, the left side has root - 1 nodes and the right side nodes - root. Add dp[root - 1] * dp[nodes - root] to dp[nodes], because any left shape can pair with any right shape.

4

Return the count for n nodes

After the outer loop, dp[n] holds the number of unique BSTs on the values 1 to n.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numTrees(self, n: int) -> int:
▶3 dp = [0] * (n + 1)
▶4 dp[0] = 1
▶5 for nodes in range(1, n + 1):
▶6 for root in range(1, nodes + 1):
▶7 dp[nodes] += dp[root - 1] * dp[nodes - root]
▶8 return dp[n]
trees for each size1size 0size 1size 2size 3root and its two sidesleftright×=an empty side counts as 1 tree
size 01
A root may have nothing on one side. That side still has exactly one shape, the empty one, so size 0 counts as 1. If it counted as 0, every product with an empty side would erase real trees.
trees for each size1size 01buildingsize 2size 3root and its two sides1emptyempty0 nodes0 nodes1×1=1size 1, root 1 → 1 tree, total 1
size1
root1
left × right1 × 1
total1
With 1 at the root, the BST rule sends no values left and no values right. The left side has 1 shape and the right side 1; any left shape pairs with any right one, so they multiply to 1. That was the last root, so size 1 has 1 trees.
trees for each size1size 01size 11buildingsize 3root and its two sides1empty20 nodes1 node1×1=1size 2, root 1 → 1 tree, total 1
size2
root1
left × right1 × 1
total1
With 1 at the root, the BST rule sends no values left and the values 2 right. The left side has 1 shape and the right side 1; any left shape pairs with any right one, so they multiply to 1.
trees for each size1size 01size 12buildingsize 3root and its two sides21empty1 node0 nodes1×1=1size 2, root 2 → 1 tree, total 2
size2
root2
left × right1 × 1
total2
With 2 at the root, the BST rule sends the values 1 left and no values right. The left side has 1 shape and the right side 1; any left shape pairs with any right one, so they multiply to 1. That was the last root, so size 2 has 2 trees.
trees for each size1size 01size 12size 22buildingroot and its two sides1empty2 to 30 nodes2 nodes1×2=2size 3, root 1 → 2 trees, total 2
size3
root1
left × right1 × 2
total2
With 1 at the root, the BST rule sends no values left and the values 2 to 3 right. The left side has 1 shape and the right side 2; any left shape pairs with any right one, so they multiply to 2.
trees for each size1size 01size 12size 23buildingroot and its two sides2131 node1 node1×1=1size 3, root 2 → 1 tree, total 3
size3
root2
left × right1 × 1
total3
With 2 at the root, the BST rule sends the values 1 left and the values 3 right. The left side has 1 shape and the right side 1; any left shape pairs with any right one, so they multiply to 1.
trees for each size1size 01size 12size 25buildingroot and its two sides31 to 2empty2 nodes0 nodes2×1=2size 3, root 3 → 2 trees, total 5
size3
root3
left × right2 × 1
total5
With 3 at the root, the BST rule sends the values 1 to 2 left and no values right. The left side has 2 shapes and the right side 1; any left shape pairs with any right one, so they multiply to 2. That was the last root, so size 3 has 5 trees.
trees for each size1size 01size 12size 25size 3root and its two sidesleftright×=3 nodes → 5 unique trees
answer5
Every root from 1 to 3 has been tried and different roots always give different trees, so 5 is the full count for 3 nodes.
05

Catalan number formula

The DP recurrence is exactly the one that defines the Catalan numbers, so dp[n] is the nth Catalan number. Consecutive Catalan numbers satisfy C(i + 1) = C(i) × 2(2i + 1) / (i + 2), and the division is always exact. Starting from C(0) = 1, apply it n times. The product before dividing can pass 2³¹ (for n = 19 it reaches about 3.5 × 10¹⁰), so C++ and Java keep it in 64 bits.

▶1class Solution:
▶2 def numTrees(self, n: int) -> int:
▶3 c = 1
▶4 for i in range(n):
▶5 c = c * 2 * (2 * i + 1) // (i + 2)
▶6 return c
06

Common pitfalls

Adding the two sides instead of multiplying

✗ Wrong
dp[nodes] += dp[root - 1] + dp[nodes - root]
✓ Right
dp[nodes] += dp[root - 1] * dp[nodes - root]

With root 1 in a 3-node tree, the left side is empty (1 way) and the right side has 2 nodes (2 ways). Every left shape pairs with every right shape, so that root gives 1 × 2 = 2 trees, not 1 + 2 = 3. Adding already reports 2 trees for a single node, and 18 instead of 5 for n = 3.

Dividing first in the Catalan formula

✗ Wrong
c = c * (2 * (2 * i + 1) // (i + 2))
✓ Right
c = c * 2 * (2 * i + 1) // (i + 2)

Only the whole product is divisible by i + 2, not 2(2i + 1) on its own. At i = 1 the bracket is 6 // 3 = 2, which happens to be fine, but at i = 2 it is 10 // 4 = 2 instead of 2.5, so n = 3 comes out 4 instead of 5.

07

Edge cases

n = 1

One root, two empty sides: dp[0] × dp[0] = 1, so there is exactly one tree.

08

Complexity

Time
O(n²)
Space
O(n)
Size k tries k roots, so the work is 1 + 2 + … + n, about n²/2 products, which is 190 for the largest input. The table has n + 1 entries.
09

Unique Binary Search Trees FAQ

Why does the answer only depend on n and not on the values?

A BST's shape is decided by the relative order of its values, and any n distinct values have the same order pattern as 1 to n. That is also why the subtree on 6, 7, 8 can be counted with dp[3].

How do I return the actual trees?

That is Unique Binary Search Trees II (LeetCode 95). It uses the same root split, but recursively builds every left and right subtree for a value range and joins each pair under a new root, so it costs about as much as the number of trees.

How fast does the count grow?

Roughly 4ⁿ divided by n^1.5. The values for n = 1 to 8 are 1, 2, 5, 14, 42, 132, 429, 1430, and n = 19 is the last size whose answer fits in a signed 32-bit integer.