给定一个整数 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
完整代码
参考:leetcode题解
递归构建
基本思想:循环构建以每一个节点为根的二叉搜索树,以递归的形式构建树的左右子树
说明:递归函数传入的参数(二叉搜索树的起始节点(s)和终止节点(e))
- 递归终止条件:s>e:在结果序列中存入空节点;s=e:将该节点存入结果序列中
- 循环构建以节点i为根节点的二叉搜索树:
递归构建左子二叉搜索树
递归构建右子二叉搜索树
合并成以i为根的二叉搜索树
/**
* 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 {
public:
vector<TreeNode*> generateTrees(int n) {
//递归构建
vector<TreeNode*> res;
if(n==0)
return res;
return build(1,n);
}
private:
vector<TreeNode*> build(int s,int e){
vector<TreeNode*> res;
if(s>e){
res.push_back(NULL);
return res;
}
if(s==e){
TreeNode *root=new TreeNode(s);
res.push_back(root);
return res;
}
//以每一个节点为根,递归构建二叉搜索树
for(int i=s;i<=e;++i){
//构建根的左右子树
vector<TreeNode*> lt=build(s,i-1);//存储左子树的所有可能的二叉搜索树
vector<TreeNode*> rt=build(i+1,e);//存储右子树的所有可能的二叉搜索树
//将所有情况合成以i为根的一棵树
for(auto clt:lt){//for(int j=0;j<lt.size();++j)
for(auto crt:rt){//for(int k=0;k<rt.size();++k)
TreeNode *root=new TreeNode(i);
root->left=clt;
root->right=crt;
res.push_back(root);
}
}
}
return res;
}
};
动态规划
基本思想:
cell[i]:存放长度为i的二叉搜索树的所有情况
这里十分巧妙的一点是:
- 以长度为2为例说明[1,2]所构成的二叉搜索树的结构其实和[97,98]所构成的二叉搜索树的结构是一样的,只不过每一个节点在[1,2]所构成的二叉树的基础上加了个偏移量96
详细思路参考:leetcode题解
/**
* 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 {
public:
vector<TreeNode*> generateTrees(int n) {
//用动态规划来实现,动态规划的数组指示构建长度为i的二叉搜索树的每一种情况
vector<vector<TreeNode*>> cell;
vector<TreeNode*> cur;
if(n==0)
return cur;
cur.push_back(NULL);
cell.push_back(cur);
for(int i=1;i<=n;++i){//长度为i的二叉搜索树
cur.clear();
for(int j=1;j<=i;++j){//以j为根的二叉搜索树,只需考虑到i,其余用偏移来处理
int ll=j-1;//左子树的长度
int rl=i-j;//右子树的长度
for(auto clt:cell[ll]){
for(auto crt:cell[rl]){
TreeNode *root=new TreeNode(j);
root->left=clt;
root->right=clone(crt,j);
cur.push_back(root);
}
}
}
cell.push_back(cur);
}
return cell[n];
}
TreeNode* clone(TreeNode* n, int offset){
if(n==NULL){
return NULL;
}
TreeNode *root=new TreeNode(n->val+offset);
root->left=clone(n->left,offset);
root->right=clone(n->right,offset);
return root;
}
};
来源:CSDN
作者:qq_31672701
链接:https://blog.csdn.net/qq_31672701/article/details/103464870