95. Unique Binary Search Trees II (Medium)
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: DFS
/**
* 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 {
vector<TreeNode*> dfs(int start, int end) {
if (start > end) return vector<TreeNode*>(1,NULL);
vector<TreeNode*> subTree;
for (int i = start; i <= end; ++i) {
vector<TreeNode*> leftSubTree = dfs(start,i-1);
vector<TreeNode*> rightSubTree = dfs(i+1,end);
for (int j = 0; j < leftSubTree.size(); ++j) {
for (int k = 0; k < rightSubTree.size(); ++k) {
TreeNode* root = new TreeNode(i);
root->left = leftSubTree[j];
root->right = rightSubTree[k];
subTree.push_back(root);
}
}
}
return subTree;
}
public:
vector<TreeNode*> generateTrees(int n) {
if (n == 0) return {};
return dfs(1,n);
}
};