You have n nodes holding the values 1 to n, each value once. Count how many differently shaped binary search trees you can build from them.
In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. Two trees count as different if their shapes differ; since the values are fixed by the shape, that is the same as the trees being different.
Example 1
Input: n = 4 Output: 14 Why: roots 1, 2, 3, 4 give 5 + 2 + 2 + 5 trees
2 more examples and the constraints
Example 2
Input: n = 2 Output: 2 Why: root 1 with 2 on its right, or root 2 with 1 on its left
Example 3
Input: n = 5 Output: 42 Why: 14 + 5 + 4 + 5 + 14, one term per root
Constraints
- 1 ≤ n ≤ 19
- The answer for n = 19 is 1,767,263,190, which fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with memoO(n²)
- Bottom-up tableO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 19 | Verdict |
|---|---|---|---|
| Recursion with memo | O(n²) | Passes; mirrors the idea | |
| Bottom-up table | O(n²) | Best; no recursion |
n = number of nodes. Plain recursion without a memo grows exponentially.
Edge cases to test
- n = 1. A single node is one tree, so the answer is 1.
- The empty side. When the root is the smallest or largest value, one side is empty.
g[0]must be 1, or that root adds nothing. - Largest n. n = 19 gives 1,767,263,190; no partial sum gets bigger than the answer, so int is enough.
- Symmetry. Root r and root n + 1 − r give the same count, which is a handy check: for n = 4, 5 + 2 + 2 + 5.
Common mistakes
- Setting
g[0] = 0, which wipes out every tree whose root is at one end. - Adding the left and right counts instead of multiplying them.
- Thinking the actual values matter; only how many nodes go on each side does.
How to talk through it
- 1Clarify. Are we counting shapes, not listing the trees? Are the values exactly 1 to n?
- 2Fix the root. Root r forces 1 to r − 1 left and r + 1 to n right; the sides are independent.
- 3Write the recurrence. g[k] is the sum over roots of g[r − 1] × g[k − r], with g[0] = 1.
- 4Fill the table. Sizes from small to large, two loops, O(n²). Mention the Catalan closed form.
- 5Test out loud. Check g[2] = 2, g[3] = 5 and g[4] = 14 by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?