95. Unique Binary Search Trees II
1. Description
Given an integer n, return all the structurally unique BST’s (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
2. Example
Example 1:
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Example 2:
Input: n = 1
Output: [[1]]
3. Constraints
- 1 <= n <= 8
4. Solutions
Brute Force
I don’t know how to calculate the complexity 😬
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
auto result = generate_trees(1, n);
return result;
}
private:
vector<TreeNode *> generate_trees(const int left, const int right) {
if (left <= right) {
vector<TreeNode *> result;
for (int i = left; i <= right; ++i) {
auto left_trees = generate_trees(left, i - 1);
auto right_trees = generate_trees(i + 1, right);
for (int l = 0; l < left_trees.size(); ++l) {
for (int r = 0; r < right_trees.size(); ++r) {
TreeNode *root = new TreeNode(i);
root->left = left_trees[l];
root->right = right_trees[r];
result.push_back(root);
}
}
}
return result;
}
return {nullptr};
}
};