Unique Binary Search Trees II - Problem
Generate All Unique Binary Search Trees

Given an integer n, your task is to generate all structurally unique Binary Search Trees (BSTs) that store exactly n nodes with unique values from 1 to n.

A Binary Search Tree is a binary tree where:
• Left subtree contains nodes with values less than the root
• Right subtree contains nodes with values greater than the root
• Both left and right subtrees are also BSTs

What makes trees structurally unique?
Trees are considered structurally different if they have different shapes or different arrangements of nodes, even if they contain the same values.

Example: For n = 3, we need to find all unique BSTs using values {1, 2, 3}. Different root choices and arrangements create structurally different trees.

Return the answer as a list of tree root nodes in any order.

Input & Output

example_1.py — Basic Case
$ Input: n = 3
Output: 5 unique BST structures using values [1,2,3]
💡 Note: For n=3, we can create 5 structurally unique BSTs: (1) root=1, right subtree=2→3; (2) root=1, right subtree=3←2; (3) root=2, left=1, right=3; (4) root=3, left subtree=1→2; (5) root=3, left subtree=2←1
example_2.py — Minimal Case
$ Input: n = 1
Output: 1 unique BST with single node [1]
💡 Note: With only one node, there's exactly one way to build the BST - a single node with value 1
example_3.py — Small Case
$ Input: n = 2
Output: 2 unique BST structures using values [1,2]
💡 Note: For n=2, we get 2 unique BSTs: (1) root=1, right child=2; (2) root=2, left child=1

Constraints

  • 1 ≤ n ≤ 8
  • Each BST must contain exactly n nodes
  • Node values must be unique integers from 1 to n
  • Trees must follow BST property: left < root < right

Visualization

Tap to expand
Unique Binary Search Trees II INPUT n = 3 Values to use: 1 2 3 BST Property: root < > left right ALGORITHM STEPS 1 Base Case Empty range --> null tree 2 Pick Each Root Try i=1,2,3 as root 3 Recurse Left/Right Left: [1,i-1], Right: [i+1,n] 4 Combine Results Pair all left x right trees generate(1,3) root=1: L=[], R=[2,3] root=2: L=[1], R=[3] root=3: L=[1,2], R=[] Count = Catalan(3) = 5 C(n) = (2n)! / ((n+1)! * n!) FINAL RESULT 5 Unique BST Structures: 1 2 3 1 3 2 2 1 3 3 1 2 3 2 1 Output: 5 tree root nodes OK - 5 BSTs Found All structurally unique! Key Insight: Use divide-and-conquer recursion: for each possible root value i, recursively generate all valid left subtrees from [1, i-1] and right subtrees from [i+1, n]. Combine each left-right pair with root i. The count follows Catalan numbers: C(n) = C(0)*C(n-1) + C(1)*C(n-2) + ... + C(n-1)*C(0) TutorialsPoint - Unique Binary Search Trees II | Optimal Recursive Solution
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18 Apple 15
67.2K Views
Medium Frequency
~25 min Avg. Time
1.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