题目
Given an integer 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
分析
这道题,算是动态规划(DP)问题
- 首先每个结点都有可能成为根节点
- 构造完根节点以后分别构造左子节点和右子结点,并进行排列组合
- 虽然这么解释给自己听,但是递归的代码,真的超难懂
实现
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode *> res;
if (n < 1)
return res;
return generateSubTrees(1, n);
}
vector<TreeNode*> generateSubTrees(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 = generateSubTrees(start, i - 1);
vector<TreeNode*> right = generateSubTrees(i + 1, end);
for(TreeNode *l:left)
for (TreeNode *r : right)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
res.push_back(root);
}
}
return res;
}
};