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
Unique BSTs with n=3 nodes {1,2,3}123Root=1 (Tree 1)132Root=1 (Tree 2)213Root=2 (Tree 3)321Root=3 (Tree 4)312Root=3 (Tree 5)Counting Formula for Each Root ChoiceRoot = 1: left_subtrees(0 nodes) ร— right_subtrees(2 nodes) = 1 ร— 2 = 2Root = 2: left_subtrees(1 node) ร— right_subtrees(1 node) = 1 ร— 1 = 1Root = 3: left_subtrees(2 nodes) ร— right_subtrees(0 nodes) = 2 ร— 1 = 2Total: 2 + 1 + 2 = 5 unique BSTs
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.3K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen