给定一个整数 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
/**
* 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)
{
if (n == 0)
{
vector<TreeNode*> ret;
return ret;
}
return genearateTree(1,n);
}
vector<TreeNode*> genearateTree(int start, int end)
{
vector<TreeNode*> res;
if (start > end)
{
res.push_back(NULL);
return res;
}
for (int i = start; i <= end; i++)
{
vector<TreeNode*> left = genearateTree(start, i-1);
vector<TreeNode*> right = genearateTree(i + 1, end);
for (int j1 = 0; j1 < left.size(); j1++)
{
for (int j2 = 0; j2 < right.size(); j2++)
{
TreeNode* cur = new TreeNode(i);
cur->left = left[j1];
cur->right = right[j2];
res.push_back(cur);
}
}
}
return res;
}
};