Unique Binary Search Trees - Problem
Given an integer n, calculate how many structurally unique Binary Search Trees (BSTs) can be constructed using exactly n nodes with unique values from 1 to n.
A BST is structurally unique if it has a different shape or structure, regardless of the actual values. For example, with n = 3, we can form 5 different BST structures using values 1, 2, 3.
Goal: Return the total count of unique BST structures possible.
Key Insight: This is a classic application of Catalan Numbers - a mathematical sequence that appears in many combinatorial problems involving tree structures.
Input & Output
example_1.py โ Small Tree
$
Input:
n = 3
โบ
Output:
5
๐ก Note:
With nodes {1,2,3}, we can form 5 structurally different BSTs: Root=1 (2 ways), Root=2 (1 way), Root=3 (2 ways). Total = 2+1+2 = 5 unique structures.
example_2.py โ Single Node
$
Input:
n = 1
โบ
Output:
1
๐ก Note:
With only one node, there's exactly one way to form a BST: a single root node. This is a base case.
example_3.py โ Larger Tree
$
Input:
n = 4
โบ
Output:
14
๐ก Note:
With 4 nodes, we get the 4th Catalan number. Root=1: 1ร5=5 ways, Root=2: 1ร2=2 ways, Root=3: 2ร1=2 ways, Root=4: 5ร1=5 ways. Total = 5+2+2+5 = 14.
Constraints
- 1 โค n โค 19
- Answer fits in a 32-bit signed integer
- Node values are from 1 to n (consecutive integers)
Visualization
Tap to expand
Understanding the Visualization
1
Choose Foundation
Pick any number 1 to n as the root foundation
2
Divide Blocks
Smaller numbers go left, larger numbers go right
3
Count Combinations
Multiply left possibilities ร right possibilities
4
Sum All Choices
Add up results for all possible foundation choices
Key Takeaway
๐ฏ Key Insight: This is the nth Catalan Number! The pattern C(n) = ฮฃ C(i-1) ร C(n-i) appears in many tree-counting problems.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code