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
Unique BSTs: n=3 → Count All StructuresRoot = 11232 treesRoot = 22131 treeRoot = 33212 treesTotal Count: 2 + 1 + 2 = 5Answer: 5Each root choice creates different BST structures
Understanding the Visualization
1
Input
Given n=3, need to count BSTs with nodes 1,2,3
2
Process
Try each node as root, count left×right combinations
3
Output
Sum all possibilities to get total count
Key Takeaway
🎯 Key Insight: Each root choice splits nodes into left and right subtrees, and we multiply the counts of possible subtree arrangements
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
230.6K Views
Medium Frequency
~15 min Avg. Time
8.5K 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