[LeetCode] Unique Binary Search Trees II

95. Unique Binary Search Trees II

Given an integer n, return all the structurally unique BST’s (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int, vector<TreeNode*>> dp;
vector<TreeNode*> helper(int mi, int ma) {
if(dp.count(mi * 10 + ma)) return dp[mi * 10 + ma];
if(mi > ma) return {nullptr};
vector<TreeNode*> res;
for(int root = mi; root <= ma; root++) {
auto left = helper(mi, root - 1);
auto right = helper(root + 1, ma);
for(auto& l : left) {
for(auto& r : right) {
TreeNode* node = new TreeNode(root, l, r);
res.push_back(node);
}
}
}
return dp[mi * 10 + ma] = res;
}
public:
vector<TreeNode*> generateTrees(int n) {
return helper(1, n);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/unique-binary-search-trees-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.