【Leetcode】【Medium】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
解题:
按照动态规划的思路,求1~n的全部排列:
遍历1~n中的每一个数k,作为根结点,所有比k小的数放在左子树,比k大的数放在右子树;
则以k为根节点的1~n全排列 等于 k的左子树全排列 与 k的右子树全排列的组合;
由此使用递归的方法,得到所有结果。
注意,递归只需考虑三个情况:
1、确定好递归函数返回值的意义,只关注当前层的逻辑,思维不要一层一层跟着递归深入;
2、设置好门限条件,也就是递归最底层的基础返回条件;
3、防止出现无限递归,无法跳出递归层;
代码:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode *> generateTrees(int n) { 13 return __generateTrees(1, n); 14 } 15 16 vector<TreeNode *> __generateTrees (int begin, int end) { 17 vector<TreeNode *> cur_nodes_mathods; 18 if (begin > end) { 19 cur_nodes_mathods.push_back(NULL); 20 return cur_nodes_mathods; 21 } 22 23 for (int i = begin; i <= end; ++i) { 24 vector<TreeNode *> lefts = __generateTrees(begin, i - 1); 25 vector<TreeNode *> rights = __generateTrees(i + 1, end); 26 27 for (int j = 0; j < lefts.size(); ++j) { 28 for (int k = 0; k < rights.size(); ++k) { 29 TreeNode *cur_root = new TreeNode(i); 30 cur_root->left = lefts[j]; 31 cur_root->right = rights[k]; 32 cur_nodes_mathods.push_back(cur_root); 33 //delete cur_root; 34 } 35 } 36 } 37 38 return cur_nodes_mathods; 39 } 40 };