给定一个整数 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] ]
重建树一般都是递归求解
class Solution {
public:
vector<TreeNode*> generateTrees(int n)
{
if(n == 0)
return {};
return GetAns(1, n);
}
vector<TreeNode*> GetAns(int start, int end)
{
vector<TreeNode*> subTree;
if(start > end)
{
subTree.push_back(NULL);
}
else
{
for(int i = start; i <= end; i++)
{
vector<TreeNode*> left = GetAns(start, i - 1);
vector<TreeNode*> right = GetAns(i + 1, end);
for(auto l : left)
{
for(auto r : right)
{
TreeNode *root = new TreeNode(i);
root ->left = l;
root ->right = r;
subTree.push_back(root);
}
}
}
}
return subTree;
}
};