leetcode-95-树题-不同的二叉搜索树

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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) {
vector<TreeNode*> res;
if(0 == n) return res;
res = helper(1, n);
return res;
}

vector<TreeNode*> helper(int start, int end){
vector<TreeNode*> res;
if(start > end) res.push_back(NULL);

for(int i = start; i <= end; ++i){
auto lefts = helper(start, i-1);
auto rights = helper(i+1, end);
for(auto l : lefts){
for(auto r : rights){
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
res.push_back(root);
}
}
}

return res;
}
};