给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
示例:
输入: 3 输出: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3
1 class Solution { 2 public: 3 vector<TreeNode *> generateTrees(int n) { 4 if (n == 0) return {}; 5 return *generateTreesDFS(1, n); 6 } 7 vector<TreeNode*> *generateTreesDFS(int start, int end) { 8 vector<TreeNode*> *subTree = new vector<TreeNode*>(); 9 if (start > end) subTree->push_back(NULL); 10 else { 11 for (int i = start; i <= end; ++i) { 12 vector<TreeNode*> *leftSubTree = generateTreesDFS(start, i - 1); 13 vector<TreeNode*> *rightSubTree = generateTreesDFS(i + 1, end); 14 for (int j = 0; j < leftSubTree->size(); ++j) { 15 for (int k = 0; k < rightSubTree->size(); ++k) { 16 TreeNode *node = new TreeNode(i); 17 node->left = (*leftSubTree)[j]; 18 node->right = (*rightSubTree)[k]; 19 subTree->push_back(node); 20 } 21 } 22 } 23 } 24 return subTree; 25 } 26 };