Leetcode Unique Binary Search Trees II代码,本代码使用c++完成,使用dp方法中的down-up方法,并提供对树的数量的测试。
#include <iostream>
#include <unordered_set>
#include <vector>
#include <string>
using namespace std;
// 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*> trees(1, nullptr);
TreeNode *root;
TreeNode *cur;
int end = 0;
for (int i = 1; i <= n; i ++) {
end = trees.size();
for (int j = 0; j < end; j ++) {
root = cloneTree(trees[j]);
cur = root;
TreeNode *newNode = new TreeNode(0);
while(cur != NULL) {
newNode->left = cur->right;
cur->right = newNode;
trees.push_back(cloneTree(root));
cur->right = newNode->left;
newNode->left = NULL;
cur = cur->right;
}
newNode->left = root;
trees[j] = newNode;
}
}
return trees;
}
TreeNode * cloneTree(TreeNode *root) {
if (root == NULL) {
return NULL;
}
TreeNode *cloneRoot = new TreeNode(root->val);
cloneRoot->left = cloneTree(root->left);
cloneRoot->right = cloneTree(root->right);
return cloneRoot;
}
};
int main() {
Solution * so = new Solution();
vector<TreeNode*> a = so->generateTrees(1);
cout<<"numer: 1"<<", result: "<<a.size()<<endl;
a = so->generateTrees(4);
cout<<"numer: 4"<<", result: "<<a.size()<<endl;
a = so->generateTrees(5);
cout<<"numer: 5"<<", result: "<<a.size()<<endl;
}