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
解题:
按照动态规划的思路,求1~n的全部排列:
遍历1~n中的每一个数k,作为根结点,所有比k小的数放在左子树,比k大的数放在右子树;
则以k为根节点的1~n全排列 等于 k的左子树全排列 与 k的右子树全排列的组合;
由此使用递归的方法,得到所有结果。
注意,递归只需考虑三个情况:
1、确定好递归函数返回值的意义,只关注当前层的逻辑,思维不要一层一层跟着递归深入;
2、设置好门限条件,也就是递归最底层的基础返回条件;
3、防止出现无限递归,无法跳出递归层;
代码:
/**
* Definition for binary tree
* 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) {
return __generateTrees(, n);
} vector<TreeNode *> __generateTrees (int begin, int end) {
vector<TreeNode *> cur_nodes_mathods;
if (begin > end) {
cur_nodes_mathods.push_back(NULL);
return cur_nodes_mathods;
} for (int i = begin; i <= end; ++i) {
vector<TreeNode *> lefts = __generateTrees(begin, i - );
vector<TreeNode *> rights = __generateTrees(i + , end); for (int j = ; j < lefts.size(); ++j) {
for (int k = ; k < rights.size(); ++k) {
TreeNode *cur_root = new TreeNode(i);
cur_root->left = lefts[j];
cur_root->right = rights[k];
cur_nodes_mathods.push_back(cur_root);
//delete cur_root;
}
}
} return cur_nodes_mathods;
}
};