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
s思路:
1. 列举所有可能,那还是backtracking. 但又和普通的backtrack不一样。不一样的地方是,这回是构建BST,以前都是枚举所有的vector。for循环里,对每个数遍历,把这个数的左侧和右侧的数分别recursive得到所有左子树和右子树的根节点,然后在用双重for来组装即可!
//
class Solution {
public:
vector<TreeNode*> helper(int start,int end){
if(start>end) return {NULL};//
vector<TreeNode*> res;
for(int i=start;i<=end;i++){
vector<TreeNode*> l=helper(start,i-1);
vector<TreeNode*> r=helper(i+1,end);
for(int j=0;j<l.size();j++){
for(int k=0;k<r.size();k++){
TreeNode* root=new TreeNode(i);
root->left=l[j];
root->right=r[k];
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
//
vector<TreeNode*> res;
if(n==0) return res;
return helper(1,n);
}
};