Unique Binary Search Trees II - Problem
Generate All Unique Binary Search Trees
Given an integer
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
Return the answer as a list of tree root nodes in any order.
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
Understanding the Visualization
1
Choose Root
Select each possible value as the root of the BST
2
Split Range
Values less than root go to left subtree, greater values go to right
3
Recursive Build
Recursively generate all possible left and right subtrees
4
Combine All
Create new trees by combining each left subtree with each right subtree
Key Takeaway
🎯 Key Insight: The problem follows a divide-and-conquer pattern where each root choice creates independent subproblems, leading to a Catalan number of solutions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code