题目描述
Given 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
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//递归创建
vector<TreeNode *> creatTrees(int left,int right){
vector<TreeNode *> res;
if(left>right){
res.push_back(NULL);
return res;
}
for(int i=left;i<=right;i++){ //以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。该原则建树具有唯一性
vector<TreeNode *> left_res = creatTrees(left,i-1);
vector<TreeNode *> right_res = creatTrees(i+1,right);
//每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况
int lsize = left_res.size();
int rsize = right_res.size();
for(int j=0;j<lsize;j++){
for(int k=0;k<rsize;k++){
TreeNode *root = new TreeNode(i);
root->left = left_res[j];
root->right = right_res[k];
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode *> generateTrees(int n) {
//本题主要考察二叉排序树的构建
//unique-binary-search-trees-i,我们可以知道结果的数目是一个卡特兰数列,当本题需要把所有可能的二叉排序
//给构建出来要求解所有的树,自然是不能多项式时间内完成的思路是每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取
//然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况),构造好之后作为当前树的
//结果返回
return creatTrees(1,n); //从1作为root开始,到n作为root结束
}
};