Unique Binary Search Trees II
TreesDynamic Programming
MediumLeetCode #95
Problem Statement
Given an integer `n`, return all the structurally unique **binary search trees** (BSTs) which has exactly `n` nodes of unique values from `1` to `n`. Return the answer in any order.
Example
Algorithm Explanation
This problem is a follow-up to "Unique Binary Search Trees". Instead of just counting the trees, we need to generate all of them. We can use a recursive approach.
Algorithm Steps
- Recursive Function: We'll create a recursive function that takes a start and end value and returns a list of all unique BSTs that can be formed with values in that range.
- Base Case: If `start > end`, it means we have an empty subtree, so we return a list containing `null`.
- Iterate and Recurse: We iterate from `start` to `end`. For each number `i` in this range, we treat it as the root. We then make recursive calls to generate all possible left subtrees (from `start` to `i-1`) and all possible right subtrees (from `i+1` to `end`).
- Combine Subtrees: We then combine each left subtree with each right subtree to form all possible trees with `i` as the root.
Start
Generating unique BSTs for n = 3
Unique Binary Search Trees II Solution