地址:https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
思路:DFS
f(i): 以 i 为根的二叉搜索树个数
s(n): n个节点的二叉搜索树个数
s(n)=f(1) + f(2) + … + f(n)
f(i) = s(i-1)*s(n-i)
则s(n) = s(0)*s(n-1) + s(1)*s(n-2) + … + s(n-1)*s(0);
通过s(n)以 i 为根进行构造
Code:
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
if(!n) return {};
return DFS(1,n);
}
vector<TreeNode *> DFS(int l, int r){
if(l>r) return {nullptr};
vector<TreeNode *> res,L,R;
TreeNode *root;
for(int i=l;i<=r;++i)
{
L=DFS(l,i-1);
R=DFS(i+1,r);
for(int li=0;li<L.size();++li)
for(int ri=0;ri<R.size();++ri)
{
root=new TreeNode(i);
root->left=L[li];
root->right=R[ri];
res.push_back(root);
}
}
return res;
}
};