【LeetCode】95. Unique Binary Search Trees II(C++)
地址:https://leetcode.com/problems/unique-binary-search-trees-ii/
题目:
Given an integer , generate all structurally unique BST’s (binary search trees) that store values … .
Example:
理解:
上一道题求的是个数,这道题要把所有的二叉树列出来。结果返回的是所有二叉树的根结点。
还是用递归的思想,把当前的结点作为根结点,生成左边和右边的所有子bst,然后再组合起来。
递归实现:
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (!n) return{};
return generate(1, n);
}
private:
vector<TreeNode*> generate(int start, int end) {
vector<TreeNode*> res;
if (start > end) res.push_back(nullptr);
else if (start == end) res.push_back(new TreeNode(start));
else {
for (int i = start; i <= end; ++i) {
vector<TreeNode*> l = generate(start, i - 1);
vector<TreeNode*> r = generate(i + 1, end);
for(int j=0;j<l.size();++j)
for (int k = 0; k < r.size(); ++k) {
TreeNode* h = new TreeNode(i);
h->left = l[j];
h->right = r[k];
res.push_back(h);
}
}
}
return res;
}
};
非递归实现1:
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (n == 0) return{};
vector<vector<TreeNode*>> dp(n + 1);
dp[0] = vector<TreeNode*>{ nullptr };
dp[1] = vector<TreeNode*>{ new TreeNode(1) };
for (int i = 2; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
for (TreeNode* nodel : dp[j]) {
for (TreeNode* noder : dp[i - j - 1]) {
TreeNode* node = new TreeNode(j + 1);
node->left = nodel;
node->right = clone(noder, j + 1);
dp[i].push_back(node);
}
}
}
}
return dp.back();
}
private:
TreeNode* clone(TreeNode* root, int offset) {
if (!root) return nullptr;
TreeNode* tmp = new TreeNode(root->val + offset);
tmp->left = clone(root->left, offset);
tmp->right = clone(root->right, offset);
return tmp;
}
};
非递归实现2:
没看懂,先存一下吧。。
Share a C++ DP solution with O(1) space
class Solution {
public:
TreeNode* clone(TreeNode* root) {
if (root == nullptr)
return nullptr;
TreeNode* newroot = new TreeNode(root->val);
newroot->left = clone(root->left);
newroot->right = clone(root->right);
return newroot;
}
vector<TreeNode *> generateTrees(int n) {
if(!n) return {};
vector<TreeNode *> res(1, nullptr);
for (int i = 1; i <= n; i++) {
vector<TreeNode *> tmp;
for (int j = 0; j<res.size(); j++) {
TreeNode* oldroot = res[j];
TreeNode* root = new TreeNode(i);
TreeNode* target = clone(oldroot);
root->left = target;
tmp.push_back(root);
if (oldroot != nullptr) {
TreeNode* tmpold = oldroot;
while (tmpold->right != nullptr) {
TreeNode* nonroot = new TreeNode(i);
TreeNode *tright = tmpold->right;
tmpold->right = nonroot;
nonroot->left = tright;
TreeNode *target = clone(oldroot);
tmp.push_back(target);
tmpold->right = tright;
tmpold = tmpold->right;
}
tmpold->right = new TreeNode(i);
TreeNode *target = clone(oldroot);
tmp.push_back(target);
tmpold->right = nullptr;
}
}
res = tmp;
}
return res;
}
};