Unique Binary Search Trees - Problem
Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.
A Binary Search Tree (BST) is a tree where for each node:
- All values in the left subtree are less than the node's value
- All values in the right subtree are greater than the node's value
Structurally unique means trees with different shapes, even if they contain the same values in different arrangements.
Input & Output
Example 1 — Small Case
$
Input:
n = 3
›
Output:
5
💡 Note:
With 3 nodes (1,2,3), we can form 5 structurally unique BSTs: root=1 gives 2 trees, root=2 gives 1 tree, root=3 gives 2 trees. Total: 2+1+2=5
Example 2 — Base Case
$
Input:
n = 1
›
Output:
1
💡 Note:
With only 1 node, there's exactly 1 way to form a BST - just a single node tree
Example 3 — Two Nodes
$
Input:
n = 2
›
Output:
2
💡 Note:
With 2 nodes (1,2), we can form 2 BSTs: root=1 with right child 2, or root=2 with left child 1
Constraints
- 1 ≤ n ≤ 19
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code