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
思路:通过递归实现。我们设置一个生成节点编号st到ed的子树的递归函数,对于给定的st到ed,我们枚举中间的每一个数当作root节点,假设数为i,则继续调用参数为st到i-1以及i+1到ed的该函数生成所有左孩子和右孩子子树。
1 /**
2 * Definition for a binary tree node.
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 gen_sub(1, n);
14 }
15 vector<TreeNode*> gen_sub(int st, int ed)
16 {
17 vector<TreeNode*> res;
18 if (st > ed)
19 res.push_back(NULL);
20 for (int i = st; i <= ed; i++)
21 {
22 vector<TreeNode*> lnodes = gen_sub(st, i - 1);
23 vector<TreeNode*> rnodes = gen_sub(i + 1, ed);
24 for (TreeNode *ln : lnodes)
25 for (TreeNode *rn : rnodes)
26 {
27 TreeNode *root = new TreeNode(i);
28 root->left = ln;
29 root->right = rn;
30 res.push_back(root);
31 }
32 }
33 return res;
34 }
35 };