题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/
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
思路: 递归构造左右子树。比较困难的是如何存储每一棵树。递归的产生每一个子树的左右节点,构造当前节点,最后可以的得到完整的一棵树。当前i节点的左节点可以是(1,i-1)的所有节点,同样右节点可以是(i+1, n)的所有节点,因此枚举所有的左右节点的可能值,最终得到所有的树。
具体代码如下:
/**
* 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*> DFS(int n, int k1, int k2)
{
if(k1 > k2) return vector<TreeNode*>{NULL};
vector<TreeNode*> result;
for(int i = k1; i <= k2; i++)
{
auto vec1 = DFS(n, k1, i-1), vec2 = DFS(n, i+1, k2);
for(auto val1: vec1)
{
for(auto val2: vec2)
{
TreeNode *root = new TreeNode(i);
root->left = val1, root->right = val2;
result.push_back(root);
}
}
}
return result;
}
vector<TreeNode*> generateTrees(int n) {
if(n <=0) return {};
return DFS(n, 1, n);
}
};