Unique Binary Search Trees II

Unique Binary Search Trees II

Description:

Given n, generate all structurally unique BST’s (binary search trees) that store values 1…n.

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

分析:

思路跟Unique Binary Search Trees很像。

考虑根节点时i的时候,则比i小的都在左子树,比i大的都在右子树。但是此时左、右子树都是多种情况的,所以还需要对左、右子树的所有情况进行组合。

注意:这个博客指出用指针的话可以节省空间,没有仔细去看。

参考:

Code:

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
41
42
43
44
45
46
47
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @paramn n: An integer
* @return: A list of root
*/
vector<TreeNode *> generateTrees(int n) {
// write your code here
return dfs(1, n);
}

vector<TreeNode *> dfs(int min, int max) {
vector<TreeNode *> rs;
if (min > max) {
rs.push_back(nullptr);
return rs;
}

for (int i = min; i <= max; i++) {
vector<TreeNode *> left = dfs(min, i-1);
vector<TreeNode *> right = dfs(i+1, max);

for(int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
TreeNode *root = new TreeNode(i);
root->left = left[j];
root->right = right[k];
rs.push_back(root);
}
}
}

return rs;
}
};