1. 题目
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
2. 思路
递归的方式处理,对于N各节点的二叉树,分别对应的就是左边i个,右边N-i-1个,根节点一个。i的取值范围是0到N-1. 初始为0个的场景即可。这里为了降低一次递归,把一个的场景也放在初始值里。
3. 代码
/**
* 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) {
vector<TreeNode*> ret;
return ret;
}
return generateTrees(n, 1);
}
vector<TreeNode*> generateTrees(int n, int val_start) {
vector<TreeNode*> ret;
if (n == 0) {
ret.push_back(NULL);
return ret;
}
if (n == 1) {
ret.push_back(new TreeNode(val_start));
return ret;
}
for (int i = 0; i < n; i++) {
vector<TreeNode*> left = generateTrees(i, val_start);
vector<TreeNode*> right = generateTrees(n-1-i, val_start+i+1);
for (int l = 0; l < left.size(); l++) {
for (int r = 0; r < right.size(); r++) {
TreeNode* root = new TreeNode(val_start+i);
root->left = left[l];
root->right = right[r];
ret.push_back(root);
}
}
}
return ret;
}
};