Question
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
Solution
分治的思想,分别求出1~n个节点为根节点构成的BST.
例如 k, 1<= k <= n; 为根节点的问题可以划分为,左子树和右子树,左子树中的节点值为1~k-1,然后1~k-1分别为根节点,同理右子树。右子树中的节点值为k+1~n,然后k+1~n分别为根节点,以此类推。
Code
/**
* 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)
return vector<TreeNode*>();
else
return generateSubTree(1, n);
}
vector<TreeNode*> generateSubTree(int s, int e) {
vector<TreeNode*> res;
if (s > e) {
res.push_back(NULL);
return res;
}
for (int i = s; i <= e; i++) {
vector<TreeNode*> left = generateSubTree(s, i - 1);
vector<TreeNode*> right = generateSubTree(i + 1, e);
// 所有组合 = size(left) * size(right)
for (TreeNode* p : left) {
for (TreeNode* q : right) {
struct TreeNode* root = new TreeNode(i);
root->left = p;
root->right = q;
res.push_back(root);
}
}
}
return res;
}
};