Unique Binary Search Trees II
题目描述:(输出用1–n这几个数字能组成的所有BST.)
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
\
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
思路:
BST(二叉排序树):中序遍历的结果为非递减序列,并且节点(个数和值)相同的不同二叉树的中序遍历结果都相同;
当左子树的节点个数确定后,右子树的个数也随之确定;
当节点个数为0或1时,二叉树只有1种,表示为f(0)=1,f(1)=f(0)*f(0);
当节点个数为2时,总的种类数=左子树为空f(0)*右子树不为空f(1)+左子树不为空f(1)*右子树为空f(0),即f(0)*f(1)+f(1)*f(0)=2种;
当节点个数为3时,有左子树为空f(0)*右子树不为空f(2)+左子树不为空f(2)*右子树为空f(0)+左右子树均不为空f(1)*f(1),即f(0)*f(2)+f(2)*f(0)+f(1)*f(1)=1*2+2*1+1*1=5种;
……
当节点个数为n时,结果为f(0)*f(n-1)+f(1)*f(n-2)+……+f(n-2)*f(1)+f(n-1)*f(0);
这个和斐波拉契数很像,他是卡特兰数。卡特兰数的具体链接地址为:https://mp.youkuaiyun.com/postedit/81946818
/**
* 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 *> generateTrees(int n) {
if (n <= 0)
return helper(1, 0);//一个节点就能创建一棵树,为了减少递归
return helper(1,n);//将结点个数传进去
}
private:
vector<TreeNode*> helper(int start,int end)
{
vector<TreeNode*> subTree;
if(start>end)//判断
{
subTree.push_back(NULL);
return subTree;
}
for (int k = start; k <= end; k++)
{
// 假设k为根节点,根节点左边是左子树,右边是右子树,一分为二,依次往下递归
//返回不同二叉树的根节点,有几个就返回几个根节点,然后装进容器里面
vector<TreeNode*> leftSubs = helper(start, k - 1);
vector<TreeNode*> rightSubs = helper(k + 1, end);
//左子右子树和根节点结合
//以k为根节点的树的个数,等于左子树的个数乘以右子树的个数
for(int i=0;i<leftSubs.size();i++)//for (auto i : leftSubs)
{
for(int j=0;j<rightSubs.size();j++)// for (auto j : rightSubs)
{
TreeNode *node = new TreeNode(k);//为每个树申请新空间
node->left =leftSubs[i];//左子树
node->right = rightSubs[j];//右子树
subTree.push_back(node);//根节点
}
}
}
return subTree;//返回树
}
};