1、二叉搜索树个数
leetcode 96. Unique Binary Search Trees
给定n,求1-n有多少种二叉搜索树
利用dfs,memo记录已访问位置
class Solution {
public:
int numTrees(int n){
return dfs(1,n);
}
private:
map<pair<int,int>,int> memo;
int dfs(int l,int r){
if(l>=r) return 1;
if(memo.find({l,r})!=memo.end()){
return memo[{l,r}];
}
int ans=0;
for(int i=l;i<=r;i++ ){
ans+=dfs(l,i-1)*dfs(i+1,r);
}
memo[{l,r}]=ans;
return ans;
}
};
2、二叉搜索树所有可能情况
leetcode 95. Unique Binary Search Trees II
给定n,求1-n的二叉搜索树所有可能情况
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
return genTrees(1,n);
}
vector<TreeNode*> genTrees(int start,int end){
vector<TreeNode*> res;
if(start>end) return res;
if(start==end) {
res.push_back(new TreeNode(start));
return res;
}
for(int i=start;i<=end;i++){
vector<TreeNode*> leftTrees=genTrees(start, i-1);
vector<TreeNode*> rightTrees=genTrees(i+1,end);
if(leftTrees.size()>0 && rightTrees.size()>0){
for(TreeNode* lnode: leftTrees)
{
for(TreeNode* rnode: rightTrees)
{
TreeNode* root = new TreeNode(i);
root->left = lnode;
root->right = rnode;
res.push_back(root);
}
}
}
else if(leftTrees.size()>0){
for(TreeNode* lnode:leftTrees){
TreeNode* root =new TreeNode(i);
root->left=lnode;
res.push_back(root);
}
}
else if ( rightTrees.size() > 0 ) {
for (TreeNode* rnode: rightTrees ) {
TreeNode* root = new TreeNode( i );
root->right = rnode;
res.push_back( root );
}
}
}
return res;
}
};