力扣第95题 不同的二叉搜索树II
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<TreeNode*> generateTree(int start, int end)
{
vector<TreeNode*> vect;
if (start > end)
{
vect.push_back(NULL);
return vect;
}
for (int i = start; i <= end; i++)
{
vector<TreeNode*> left = generateTree(start, i - 1);
vector<TreeNode*> right = generateTree(i + 1, end);
for (vector<TreeNode*>::iterator itorl = left.begin(); itorl != left.end(); itorl++)
{
for (vector<TreeNode*>::iterator itorr = right.begin(); itorr != right.end(); itorr++)
{
TreeNode* pNode = new TreeNode(i);
pNode->left = *itorl;
pNode->right = *itorr;
vect.push_back(pNode);
}
}
}
return vect;
}
vector<TreeNode*> generateTrees(int n)
{
vector<TreeNode*> vect;
if (n <= 0)
{
return vect;
}
return generateTree(1, n);
}
原文地址:https://www.cnblogs.com/woodjay/p/12370094.html
时间: 2024-11-09 21:10:34