95 Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> helper(vector<int>& nums, int i, int j) {
vector<TreeNode*> res;
if ( i > j ) { res.push_back(NULL); return res; }
for ( int k = i; k <= j; k++ ) {
auto res_left = helper(nums, i, k-1);
auto res_right = helper(nums, k+1, j);
int nl = res_left.size(), nr = res_right.size();
for ( int il = 0; il <= nl-1; il++ ) {
for ( int ir = 0; ir <= nr-1; ir++ ) {
TreeNode *root = new TreeNode(nums[k]);
root->left = res_left[il];
root->right = res_right[ir];
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if ( n == 0 ) return res;
vector<int> nums;
for ( int i = 1; i <= n; i++ ) nums.push_back(i);
res = helper(nums, 0, n-1);
return res;
}
};