LeetCode 95 Unique Binary Search Trees II
概述
https://leetcode.com/problems/unique-binary-search-trees-ii/
递归法
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
return helper(1, n);
}
vector<TreeNode*> helper(int l, int r) {
vector<TreeNode*> ans;
if (l > r) {
ans.push_back(nullptr); // make sure there is at least one emelent
return ans;
}
for (int i = l; i <= r; i ++) {
auto lnodes = helper(l, i - 1);
auto rnodes = helper(i + 1, r);
for (auto lnode : lnodes) {
for (auto rnode : rnodes) {
ans.push_back(new TreeNode(i, lnode, rnode));
}
}
}
return ans;
}
};