# 不同的二叉搜索树 II

给你一个整数 n ,请你生成并返回所有由 n 个节点组成且节点值从 1n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。

 

示例 1:

输入:n = 3

输出:
[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]

示例 2:

输入:n = 1

输出:
[[1]]

 

提示:

  • 1 <= n <= 8

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; 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) {} }; ``` ### after ```cpp ``` ## 答案 ```cpp class Solution { public: vector generateTrees(int n) { if (n <= 0) return vector{}; return generate(1, n); } vector generate(int begin, int end) { vector ret; if (begin > end) { return ret; } for (int i = begin; i <= end; ++i) { vector lSubs = generate(begin, i - 1); vector rSubs = generate(i + 1, end); for (auto l : lSubs) { for (auto r : rSubs) { TreeNode *root = new TreeNode(i); root->left = l; root->right = r; ret.push_back(cloneTree(root)); } } } return ret; } }; ``` ## 选项 ### A ```cpp class Solution { public: vector generateTrees(int n) { vector res; if (n < 1) return res; res = creatTree(1, n); return res; } vector creatTree(int start, int end) { vector res; if (start > end) { res.push_back(NULL); return res; } if (start == end) { TreeNode *node = new TreeNode(start); res.push_back(node); return res; } for (int i = start; i <= end; i++) { vector left = creatTree(start, i - 1); vector right = creatTree(i + 1, end); for (int j = 0; j < left.size(); j++) { for (int k = 0; k < right.size(); k++) { TreeNode *node = new TreeNode(i); node->left = left[j]; node->right = right[k]; res.push_back(node); } } } return res; } }; ``` ### B ```cpp class Solution { public: vector m[9][9]; vector generate(int left, int right) { if (left > right) return {nullptr}; if (!m[left][right].empty()) return m[left][right]; vector trees; for (int i = left; i <= right; i++) { vector left_all = generate(left, i - 1); vector right_all = generate(i + 1, right); for (TreeNode *l : left_all) { for (TreeNode *r : right_all) { TreeNode *root = new TreeNode(i); root->left = l; root->right = r; trees.emplace_back(root); } } } m[left][right] = trees; return trees; } vector generateTrees(int n) { return generate(1, n); } }; ``` ### C ```cpp class Solution { public: vector generateTrees(int n) { vector res; if (n == 0) { return res; } return gem(1, n); } vector gem(int start, int end) { vector res; if (start > end) { res.push_back(NULL); } for (int i = start; i <= end; i++) { vector lefts = gem(start, i - 1); vector rights = gem(i + 1, end); for (auto left : lefts) { for (auto right : rights) { TreeNode *temp = new TreeNode(i); temp->left = left; temp->right = right; res.push_back(temp); } } } return res; } }; ```