给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
示例:
输入: 3 输出: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
思路:递归方法
选第k个元素作为根,调用自身求左子树,调用自身求右子树,再将根与左子树和右子树排列组合形成结果
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static const int _ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
vector<TreeNode*> generateTrees(int n,int loc){ //n表示规模,loc表示起始位置
vector<TreeNode*> ret;
if(n == 0){
return ret;
}
if(n == 1){
TreeNode *t = new TreeNode(loc);
ret.push_back(t);
return ret;
}
if(n == 2){
TreeNode *t1 = new TreeNode(loc),*t2 = new TreeNode(loc+1);
TreeNode *t3 = new TreeNode(loc),*t4 = new TreeNode(loc+1);
t1 -> right = t2;
t4 -> left = t3;
ret.push_back(t1);
ret.push_back(t4);
return ret;
}
for(int i = 0; i < n; i++){ //选第i+1个元素作为根
vector<TreeNode*> t1,t2;
t1 = generateTrees(i,loc); //求左子树
t2 = generateTrees(n-1-i,loc+i+1); //求右子树
if(t1.empty()) t1.push_back(NULL);
if(t2.empty()) t2.push_back(NULL);
for(int j = 0; j < t1.size(); j++){ //排列组合
for(int k = 0; k < t2.size(); k++){
TreeNode *temp = new TreeNode(loc+i);
temp -> left = t1[j];
temp -> right = t2[k];
ret.push_back(temp);
}
}
}
return ret;
}
vector<TreeNode*> generateTrees(int n) {
return generateTrees(n,1);
}
};
效率:
99.72%